Contents

Develop
2017.06.27 14:38

[coding] Find all anagrams in a string

조회 수 1146 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

코딩테스트 관련 URL

https://leetcode.com/problems/find-all-anagrams-in-a-string/#/description



# 내가 푼 내용

/**
 * @param {string} s
 * @param {string} p
 * @return {number[]}
 */
var findAnagrams = function(s, p) {
    var res = Array();
    
    if(s.length < p.length){
        return res;
    }
    
    p1 = Array.from(p).sort().join("");
    
    for(var i=0; i<=s.length-p.length; i++){
        var s1 = s.substring(i, p.length + i);
        s1 = Array.from(s1).sort().join("");
        if(s1 == p1){
            res.push(i);
        }
    }
    
    return res;
};

var s = "cbaebabacd";
var p = "abc";
var r = findAnagrams(s, p);

console.log(r);



# 봐도 모르는 넘사벽 정답을 그냥 Javascript로 변경만 한거 ㅋㅋ

/**
 * @param {string} s
 * @param {string} p
 * @return {number[]}
 */
var findAnagrams = function(s, p) {
    var res = Array();
    
    if(s.length < p.length){
        return res;
    }
    
    var hash = new Array(256).fill(0);
    var left = 0;
    var right = 0;
    var count = p.length;
    
    for(var i=0; i<p.length; i++){
	    //hash[p.charCodeAt(i)] = (hash[p.charCodeAt(i)] || 0) + 1;
	    hash[p.charCodeAt(i)]++;
	    console.log("hash["+p.charCodeAt(i)+"] "+hash[p.charCodeAt(i)]);
    }
    
    while(right < s.length){
	    if (hash[s.charCodeAt(right++)]-- >= 1){
		    count--;
	    }
	    
	    if(count == 0){
		    res.push(left);
	    }
	    
	    if(right - left == p.length && hash[s.charCodeAt(left++)]++ >= 0){
		    count++;
	    }
    }
    
    return res;
};

var s = "cbaebabacd";
var p = "abc";
var r = findAnagrams(s, p);

console.log(r);



?

List of Articles
번호 분류 제목 글쓴이 날짜 조회 수
289 Develop [c][java] 소켓 프로그래밍(채팅 서버 C, 클라이언트 Java) file hooni 2003.04.23 7011
288 Develop [c] C에서 MySQL DB 사용하기~ file hooni 2003.04.23 7011
287 Develop [js] 이미지 미리 로딩하기 hooni 2003.04.23 7008
286 Develop [js] 점점 커지는 새창.. hooni 2003.04.23 6998
285 Develop [php] 메모장 - 웅지학원 ([c] mysql 백업프로그램 포함) file hooni 2003.04.23 6993
284 Develop 도메인 관련 솔루션 분석할 거.. ㅋㄷ file hooni 2013.04.23 6982
283 Develop [c++] 템플릿(Template) 예제 소스.. file hooni 2013.04.23 6982
282 Develop [c] 소켓 프로그래밍 요약.. hooni 2003.04.23 6971
281 Develop [web] 웹 연동 프로그램 모음.. file hooni 2013.04.23 6960
280 Develop [c++] 트리컨트롤 스텝 2 예제.. file hooni 2013.04.23 6959
279 Develop [c] 단기과정[01/24] 정렬 알고리즘 hooni 2003.04.23 6955
278 Develop [c] 패킷 에널라이저 예제 소스(성안당) file hooni 2013.04.23 6947
Board Pagination Prev 1 ... 42 43 44 45 46 47 48 49 50 51 ... 71 Next
/ 71