Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.
Notes:
Input strings s1 and s2 are null terminated.
Examples
scramble('rkqodlw', 'world') ==> True
scramble('cedewaraaossoqqyt', 'codewars') ==> True
scramble('katas', 'steak') ==> False
(요약) 두 번째 문자열 각각 요소가 첫 번째 문자열에 모두 있는지 확인. 중복 불가.
function scramble(str1, str2) { const charIndexes = {}; for(let i = 0; i < str2.length; i++) { if(str1.indexOf(str2[i], (charIndexes[str2[i]] + 1) || '0') === -1) { return false; } charIndexes[str2[i]] ? charIndexes[str2[i]] = str1.indexOf(str2[i], charIndexes[str2[i]] + 1) : charIndexes[str2[i]] = str1.indexOf(str2[i]); } return true; }
처음에 시도했던게 반복문을 이용해서
str2
의 각 요소가str1
에 없으면false
를return
하고, 있으면str1
에서 그 문자를replace
로 치환하려고 했는데 테스트 케이스 중에 엄청 긴게 있어서 타임아웃이 나버림.그래서 요소를 찾을 때 마다 그
index
를 관리하는 객체를 하나 만들고, 처음 찾는 문자면 처음 발견한index
를 저장하고, 다음에 또 같은 문자를 찾아야되면 그 다음index
부터 검색하게 함.
끝까지 조건문을 안타면 문자가 전부 있는것이니true
를return
하게 하면 됨.