字母异位词
有效的字母异位词
class Solution { public boolean isAnagram(String s, String t) { int slen = s.length(); int tlen = t.length(); if(slen != tlen){ return false; } //借助一个数组,下标为字符 int[] c = new int[26]; for(int i =0; i < slen; i++){ c[s.charAt(i) - 'a'] ++; c[t.charAt(i) - 'a'] --; } for(int i = 0; i < 26; i++){ if(c[i] != 0){ return false; } } return true; } }
找到字符串中所有字母异位词
借助滑动窗口:
class Solution { public List<Integer> findAnagrams(String s, String p) { int[] windows = new int[26]; int[] needs = new int[26]; List<Integer> res = new ArrayList<>(); for(char ch : p.toCharArray()){ needs[ch - 'a'] ++; } int left = 0, right = 0; while(right < s.length()){ char c = s.charAt(right); //右移 right++; if(needs[c - 'a'] > 0){ //进行更新 windows[c - 'a'] ++; } //左移 while(right - left >= p.length()){ //借用工具类来比较 if(Arrays.equals(needs, windows)){ //如果都包含,添加进去 res.add(left); } char d = s.charAt(left); left++; //如果是目标字符串的字母,进行更新 if(needs[d - 'a'] > 0){ windows[d - 'a'] --; } } } return res; } }