leetcode 438. Find All Anagrams in a String
阿新 • • 發佈:2018-12-13
temp class int ram while lee all () 正在
題意:在s串中找到與p串所用字符種類,數目相同的所有子串的起始位置。初始化兩個變量start,end,diff。start,end為s串中目前正在與p串比較的子串的起始位置和終止位置。diff為這一子串與p串的差異數。當diff == 0 && (end-start+1) == p.length。則說明我們找到了一個子串,存儲start。當diff == 0時,我們需要將start前移,並相應地增加diff。說了很多,當實際上仔細想想就明白了,不難。
class Solution { public List<Integer> findAnagrams(String s, String p) { int slen = s.length(), plen = p.length(); LinkedList<Integer> ans = new LinkedList<>(); if(slen < plen) return ans; int[] c = new int [26]; for(int i=0;i<plen;i++) c[p.charAt(i)-‘a‘]++; int diff = plen; int start = 0, end = 0; while(start<=end && end < slen){ int t = s.charAt(end); if(--c[t-‘a‘] >= 0 ) diff--; while(diff == 0){ t = s.charAt(start); int temp = end - start+1; if(temp == plen) ans.add(start); if(++c[t-‘a‘] > 0) diff++; start++; } end++; } return ans; } }
leetcode 438. Find All Anagrams in a String