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?