1818 */
1919public class Solution {
2020 public List <Integer > findSubstring (String s , String [] words ) {
21- int wordsSize = words .length , wordLen = words [0 ].length (), end = s .length () - wordsSize * wordLen ;
21+ if (s == null ) return Collections .emptyList ();
22+ int len = s .length ();
23+ if (len == 0 ) return Collections .emptyList ();
24+ int wordsSize = words .length ;
25+ if (wordsSize == 0 ) return Collections .emptyList ();
26+ int wordLen = words [0 ].length (), end = len - wordsSize * wordLen ;
2227 if (end < 0 ) return Collections .emptyList ();
2328 Map <String , Integer > countMap = new HashMap <>();
2429 for (String word : words ) {
@@ -33,7 +38,7 @@ public List<Integer> findSubstring(String s, String[] words) {
3338 List <Integer > ignore = new ArrayList <>();
3439 for (int j = 0 ; ; ++j ) {
3540 int cur = i + j * wordLen ;
36- if (cur + wordLen > s . length () ) break ;
41+ if (cur + wordLen > len ) break ;
3742 String word = s .substring (cur , cur + wordLen );
3843 if (countMap .containsKey (word )) {
3944 findMap .put (word , findMap .getOrDefault (word , 0 ) + 1 );
@@ -63,52 +68,6 @@ public List<Integer> findSubstring(String s, String[] words) {
6368 return res ;
6469 }
6570
66- // public List<Integer> findSubstring(String S, String[] L) {
67- // List<Integer> res = new LinkedList<>();
68- // int N = S.length();
69- // int M = L.length; // *** length
70- // int wl = L[0].length();
71- // Map<String, Integer> map = new HashMap<>(), curMap = new HashMap<>();
72- // for (String s : L) {
73- // if (map.containsKey(s)) map.put(s, map.get(s) + 1);
74- // else map.put(s, 1);
75- // }
76- // String str = null, tmp = null;
77- // for (int i = 0; i < wl; i++) {
78- // int count = 0; // remark: reset count
79- // int start = i;
80- // for (int r = i; r + wl <= N; r += wl) {
81- // str = S.substring(r, r + wl);
82- // if (map.containsKey(str)) {
83- // if (curMap.containsKey(str)) curMap.put(str, curMap.get(str) + 1);
84- // else curMap.put(str, 1);
85- //
86- // if (curMap.get(str) <= map.get(str)) count++;
87- // if (count == M) {
88- // res.add(start);
89- // tmp = S.substring(start, start + wl);
90- // curMap.put(tmp, curMap.get(tmp) - 1);
91- // start += wl;
92- // count--;
93- // }
94- // while (curMap.get(str) > map.get(str)) {
95- // tmp = S.substring(start, start + wl);
96- // curMap.put(tmp, curMap.get(tmp) - 1);
97- // start += wl;
98- // if (curMap.get(tmp) < map.get(tmp)) count--;
99- //
100- // }
101- // } else {
102- // curMap.clear();
103- // count = 0;
104- // start = r + wl;
105- // }
106- // }
107- // curMap.clear();
108- // }
109- // return res;
110- // }
111-
11271 public static void main (String [] args ) {
11372 Solution solution = new Solution ();
11473 System .out .println (solution .findSubstring ("wordgoodgoodgoodbestword" , new String []{"word" , "good" , "best" , "good" }));
0 commit comments