1.문제
Given a pattern and a string s, find if s follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
pattern 과 s 문자열이 주어질 때 두 문자열의 패턴이 동일한지 묻는 문제이다.
Example 1
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Example 2
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Example 3
Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false
Constraints:
- 1 <= pattern.length <= 300
- pattern contains only lower-case English letters.
- 1 <= s.length <= 3000
- s contains only lowercase English letters and spaces ' '.
- s does not contain any leading or trailing spaces.
- All the words in s are separated by a single space.
2.풀이
- pattern 은 문자기준 , s 는 공백기준으로 잘라서 배열로 만들어준다.
- for문을 돌면서 각 문자들의 최초 등장 index를 새로운 문자열로 만들어준다
- 새로 만들어진 인덱스 문자열 두개를 비교한다.
/**
* @param {string} pattern
* @param {string} s
* @return {boolean}
*/
var wordPattern = function(pattern, s) { // 각 단어들의 최초 인덱스를 문자열로 만들어준다
s = s.split(' ');
pattern = pattern.split('');
if(s.length !== pattern.length) return false
let r1 = '';
let r2 = '';
for(let i = 0; i < s.length; i++) {
r1 += s.indexOf(s[i]);
r2 += pattern.indexOf(pattern[i]);
}
return r1 === r2
};
3.결과
