LeetCode 245. Shortest Word Distance III
原题链接在这里:https://leetcode.com/problems/shortest-word-distance-iii/
题目:
This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
word1 and word2 may be the same and they represent two individual words in the list.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"]
.
Given word1 = “makes”
, word2 = “coding”
, return 1.
Given word1 = "makes"
, word2 = "makes"
, return 3.
题解:
若是两个指针p1 和 p2相等时,不更新res.
Time Complexity: O(n). Space: O(1).
AC Java:
1 class Solution { 2 public int shortestWordDistance(String[] words, String word1, String word2) { 3 if(words == null){ 4 return -1; 5 } 6 7 int ind1 = -1; 8 int ind2 = -1; 9 int res = words.length; 10 11 for(int i = 0; i < words.length; i++){ 12 if(words[i].equals(word1)){ 13 ind1 = i; 14 if(ind2 != -1){ 15 res = Math.min(res, ind1 - ind2); 16 } 17 } 18 19 if(words[i].equals(word2)){ 20 ind2 = i; 21 if(ind1 != -1 && ind1 < ind2){ 22 res = Math.min(res, ind2 - ind1); 23 } 24 } 25 } 26 27 return res; 28 } 29 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步