Problem
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.
Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Input: word1 = “makes”, word2 = “coding”
Output: 1
Input: word1 = "makes", word2 = "makes"
Output: 3
Note:
You may assume word1 and word2 are both in the list.
class Solution { public int shortestWordDistance(String[] words, String word1, String word2) { Map> map = new HashMap >(); for(int i = 0; i < words.length; i++) { String word = words[i]; if (!map.containsKey(word)) map.put(word, new ArrayList<>()); map.get(word).add(i); } if (word1.equals(word2)) { List list = map.get(word1); if (list.size() < 2) return -1; int min = Integer.MAX_VALUE; for (int i = 0; i < list.size()-1; i++) { min = Math.min(min, list.get(i+1)-list.get(i)); } return min; } List list1 = map.get(word1); List list2 = map.get(word2); int min = Integer.MAX_VALUE; int i = 0, j = 0; while (i < list1.size() && j < list2.size()) { int index1 = list1.get(i), index2 = list2.get(j); if (index1 < index2) { min = Math.min(min, index2 - index1); i++; } else { min = Math.min(min, index1 - index2); j++; } } return min; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/72706.html
摘要:代碼第一次寫入就先不比較第一次寫入就先不比較哈希表法復雜度時間空間思路因為會多次調用,我們不能每次調用的時候再把這兩個單詞的下標找出來。我們可以用一個哈希表,在傳入字符串數組時,就把每個單詞的下標找出存入表中。 Shortest Word Distance Given a list of words and two words word1 and word2, return the ...
Problem Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the l...
Problem Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. Example:Assume that words = [practice, makes, perfect, coding, makes]. In...
摘要:存放過程中的所有集合為所有的結尾,則順序存放這個結尾對應的中的所有存放同一個循環的新加入的,在下一個循環再依次對其中元素進行進一步的把首個字符串放入新,再將放入,并將鍵值對放入,進行初始化 Problem Given two words (start and end), and a dictionary, find all shortest transformation sequenc...
摘要:返回字符串中每一個字符離給定的字符的最短距離。否則,當當前下標大于上一個出現字符的位置,且存在下一個字符時,距離為兩者中最小的那個。最終代碼若覺得本文章對你有用,歡迎用愛發電資助。 D49 821. Shortest Distance to a Character 題目鏈接 821. Shortest Distance to a Character 題目分析 給定一個字符串s和一個字符...
閱讀 3766·2021-11-24 09:39
閱讀 2966·2021-11-16 11:49
閱讀 2083·2019-08-30 13:54
閱讀 1109·2019-08-30 13:03
閱讀 1097·2019-08-30 11:10
閱讀 725·2019-08-29 17:10
閱讀 1253·2019-08-29 15:04
閱讀 1220·2019-08-29 13:02