@@ -40,6 +40,54 @@ Output: []
40
40
4 . 使用第二个HashMap来记录我们查到的单词。如果所有的单词都查到了,即可记录一个解。
41
41
42
42
``` java
43
+ class Solution {
44
+ public List<Integer > findSubstring (String s , String [] words ) {
45
+ List<Integer > resultList = new ArrayList<Integer > ();
46
+ if (s == null || s. length() == 0 || words == null || words. length == 0 ) {
47
+ return resultList;
48
+ }
49
+ Map<String , Integer > wordMap = new HashMap<String , Integer > ();
50
+ Map<String , Integer > foundMap = new HashMap<String , Integer > ();
51
+ for (String word: words) {
52
+ if (wordMap. containsKey(word)) {
53
+ wordMap. put(word, (wordMap. get(word) + 1 ));
54
+ } else {
55
+ wordMap. put(word, 1 );
56
+ }
57
+ }
58
+ int wordCount = words. length;
59
+ int wordLen = words[0 ]. length();
60
+ int allLen = wordLen * wordCount;
61
+
62
+ for (int i = 0 ; i <= s. length() - allLen; i++ ) {
63
+ foundMap. clear();
64
+ int foundCount = 0 ;
65
+ for (int j = 0 ; j < wordCount; j++ ) {
66
+ String tempWord = s. substring(i + j * wordLen, i + (j + 1 ) * wordLen);
67
+ if (wordMap. containsKey(tempWord)) {
68
+ if (foundMap. containsKey(tempWord)) {
69
+ foundMap. put(tempWord, (foundMap. get(tempWord) + 1 ));
70
+ } else {
71
+ foundMap. put(tempWord, 1 );
72
+ }
73
+
74
+ if (foundMap. get(tempWord) > wordMap. get(tempWord)) {
75
+ break ;
76
+ }
77
+ foundCount++ ;
78
+ } else {
79
+ break ;
80
+ }
81
+ }
82
+
83
+ if (foundCount == wordCount) {
84
+ resultList. add(i);
85
+ }
86
+ }
87
+
88
+ return resultList;
89
+ }
90
+ }
43
91
44
92
```
45
93
0 commit comments