【LeetCode】245.Shortest Word Distance III(Medium)(加锁题)解题报告
2018-02-27 21:32
501 查看
【LeetCode】245.Shortest Word Distance III(Medium)(加锁题)解题报告
题目地址: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 asword2.
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.v
For example,
Assume that words = [“practice”, “makes”, “perfect”, “coding”, “makes”].
Given word1 = “makes”, word2 = “coding”, return 1.
Given word1 = “makes”, word2 = “makes”, return 3.
Note: You may assume word1 and word2 are both in the list.
有重复单词.
Solution:
Date:2018年2月27日
题目地址: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 asword2.
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.v
For example,
Assume that words = [“practice”, “makes”, “perfect”, “coding”, “makes”].
Given word1 = “makes”, word2 = “coding”, return 1.
Given word1 = “makes”, word2 = “makes”, return 3.
Note: You may assume word1 and word2 are both in the list.
有重复单词.
Solution:
//time : O(n) //space : O(1) class Solution { public int shortestWordDistance(String[] words, String word1, String word2) { int res = words.length; int a = -1; int b = -1; for(int i=0 ; i<words.length ; i++){ if(words[i].equals(word1)){ a = i; } if(words[i].equals[word2]){ if(word1.equals(word2)){ a = b; } b = i; } if(a != -1 && b != -1){ res = Math.min(res,Math.abs(a-b)); } } return res; } }
Date:2018年2月27日
相关文章推荐
- [leetcode] 245. Shortest Word Distance III 解题报告
- [Leetcode] 245. Shortest Word Distance III 解题报告
- 【LeetCode】244.Shortest Word Distance II(Medium)解题报告
- [Leetcode] 244. Shortest Word Distance II 解题报告
- 【LeetCode】216.Combination Sum III(Medium)解题报告
- [leetcode] 244. Shortest Word Distance II 解题报告
- Leetcode 245. Shortest Word Distance III (Medium) (cpp)
- 【LeetCode】55.Jump Game(Medium)解题报告
- 【LeetCode】Longest Word in Dictionary through Deleting 解题报告
- [leetcode] 123. Best Time to Buy and Sell Stock III 解题报告
- LeetCode Shortest Word Distance III
- 【LeetCode】275.H-Index II(Medium)解题报告
- 【LeetCode】732. My Calendar III解题报告
- LeetCode解题报告 108. Convert Sorted Array to Binary Search Tree [medium]
- [leetcode] 211. Add and Search Word - Data structure design 解题报告
- [LeetCode] 245. Shortest Word Distance III 最短单词距离 III
- 【LeetCode】698.Partition to K Equal Sum Subsets(Medium)解题报告
- LeetCode解题报告 413. Arithmetic Slices [medium]
- LeetCode 245. Shortest Word Distance III(最短单词距离)
- 【LeetCode】11.Container With Most Water(Medium)解题报告