Find All Anagrams
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
๋ฌธ์ ์ดํด : String์ Pattern์ด ์๋์ง, ์๋ค๋ฉด ๋ช ๋ฒ์งธ ์ธ๋ฑ์ค์์ ์กด์ฌํ๋์ง ๊ตฌํ๋ค.
Example 1: Input : s : "cbaebabacd" p : "abc" Output : [0,6]
Example 2: Input : s : "abab" p : "ab" Output : [0,1,2]
์๋ฃ๊ตฌ์กฐ : List์ด์ฉ
์๊ณ ๋ฆฌ์ฆ : Sliding Window์ ๋ฐฐ์ด์ ์ํ๋ฒณ ์์คํค์ฝ๋๋ฅผ ์ ์ฅํ์ฌ ๋น๊ตํ๋ ๋ฉ์ปค๋์ฆ ์ด์ฉ! ์ธ๋ฑ์ค๋ค์ List์ ๋ฃ๊ณ ์ด๋ฅผ ๋ฆฌํดํ๋ค. String๊ณผ Pattern ๊ฐ๊ฐ์ ์๋ ์ํ๋ฒณ ๋ฐฐ์ด์ ๋ง๋ค์ด์ ์ํ๋ฒณ์ด์๋ค๋ฉด ํด๋นํ๋ ๋ฐฐ์ด๋ฐฉ์ ๋ฐ์ดํฐ๋ฅผ 1์ฆ๊ฐํ์ฌ frequency๋ฅผ ๊ธฐ๋กํ๋ค.
์๊ณ ๋ฆฌ์ฆ์ Java๋ก ๊ตฌํ
class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        //1. ๋ด์ ๊ทธ๋ฆ ์์ฑ
        List<Integer> result = new ArrayList<>();
        //๊ธฐ์ ์ฌ๋ก ์ ์ธ!
        if(s==null||s.length()==0||p==null||p.length()==0||s.length()<p.length())
		 return result;
        //2.String s์ pattern์ ํด๋นํ๋ ์ํ๋ฒณ ๋ฐฐ์ด์ ์์ฑํ์ฌ 
        int[] pAlpha = new int[256];
        int[] sAlpha = new int[256];
        
        //2์ frequency๋ฅผ ๊ธฐ๋กํ๋ค.
        for(int i=0; i < p.length();i++) {
            pAlpha[p.charAt(i)]++;
        }
        //3.String s์ patttern์ ํฌ๊ธฐ๋งํผ, 1์ฉ ์ด๋ํ๋ค. i๋ ์์์ ,j๋ ๋์ 
        for(int i=0; i< s.length()-p.length()+1;i++) {//starting point๋ง ๊ธฐ๋กํ  ๊ฒ์ด๊ธฐ ๋๋ฌธ์ s-p์ฌ์ด์ฆ๋งํผ
            for(int j=0; j<p.length();j++) {//window ํฌ๊ธฐ!
                sAlpha[s.charAt(i+j)]++;
            }
            if(check(pAlpha,sAlpha)){
                result.add(i);
            }
        }
        return result;
    }
    private boolean check(int[] pAlpha, int[] sAlpha) {
        for(int i=0;i<pAlpha.length;i++) {
            if(pAlpha[i] != sAlpha[i])
                return false;
        }
        return true;
    }
}Last updated
Was this helpful?