严氏北美IT公司面试真题汇总和解答论坛
Would you like to react to this message? Create an account in a few clicks or log in to continue.

Find All Anagrams in String 高频题

Go down

Find All Anagrams in String 高频题 Empty Find All Anagrams in String 高频题

Post by Admin Sat Oct 21, 2017 4:36 pm

public List<Integer> findAnagramsByHashMap(String s, String p) {
List<Integer> result = new ArrayList<>();
if (s == null || s.length() == 0) {
return result;
}
if (p.length() > s.length()) {
return result;
}
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < p.length(); i++) {
char c = p.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
}
int match = 0;
for (int i = 0; i < s.length(); i++) {

char c = s.charAt(i);
if (map.containsKey(c)) {
map.put(c, map.get(c) - 1);
if (map.get(c) == 0) {
match++;
}
}

if (i >= p.length()) {
c = s.charAt(i - p.length());
if (map.containsKey(c)) {
map.put(c, map.get(c) + 1);
if (map.get(c) == 1) {
match--;
}
}
}

if (match == map.size()) {
result.add(i - p.length() + 1);
}

}
return result;
}

Admin
Admin

Posts : 124
Join date : 2017-10-21

https://csinterviewquestions.forumotion.com

Back to top Go down

Back to top

- Similar topics

 
Permissions in this forum:
You cannot reply to topics in this forum