알고리즘

[Multiple pointers] isSubsequence

selonjulie 2022. 7. 31. 12:33

Wirte a function called isSubsequence which takes two strings and checks whether the characters in the first string from a subsequence of the characters in the second string. In other words, the function should check whether the characters in the first string appear somewhere in the second string, without their order changing. 

 

두 개의 문자열을 가져와서 첫 번째 문자열의 문자가 두 번째 문자열에 있는 문자의 하위 시퀀스인지 확인하는 isSubsequence라는 함수를 작성합니다. 즉, 함수는 첫 번째 문자열의 문자가 순서를 변경하지 않고 두 번째 문자열의 어딘가에 나타나는지 확인해야 합니다.

 

isSubsequence('hello', 'hello world'); // true
isSubsequence('sing', 'sting'); // true
isSubsequence('abc', 'abracadabra'); // true
isSubsequence('abc', 'acb'); // false (order matters)

 

해결책1

function isSubsequence(str1, str2) {
  let i = 0;
  let j = 0;
  if (!str1) return true;
  while (j < str2.length) {
    if (str2[j] === str1[i]) i++;
    if (i === str1.length) return true;
    j++;
  }
  return false;
}

조건문

else if문과 else문은 옵션이다. 즉, 사용할수도 있고 사용하지 않을 수도 있다.

 

해결책2

function isSubsequence(str1, str2) {
  if(str1.length === 0) return true
  if(str2.length === 0) return false
  if(str2[0] === str1[0]) return isSubsequence(str1.slice(1), str2.slice(1))  
  return isSubsequence(str1, str2.slice(1))
}

 

'알고리즘' 카테고리의 다른 글

알고리즘 문제풀이 접근 방법  (0) 2022.08.07
Sliding Window: maxSubarraySum  (0) 2022.07.31
Divide and Conquer (binary search)  (0) 2022.07.11
Sliding window  (0) 2022.07.10
[Multiple pointers] sumZero  (0) 2022.07.03