CodeWars 코딩 문제 2021/02/16 -Scramblies
[문제]
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:
- Only lower case letters will be used (a-z). No punctuation or digits will be included.
- Performance needs to be considered
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
하게 하면 됨.
Author And Source
이 문제에 관하여(CodeWars 코딩 문제 2021/02/16 -Scramblies), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://velog.io/@hemtory/CodeWars20210216
저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
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
하게 하면 됨.
Author And Source
이 문제에 관하여(CodeWars 코딩 문제 2021/02/16 -Scramblies), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@hemtory/CodeWars20210216저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)