알고리즘 기초 다지기 프로젝트 (feat. 코드없는 프로그래밍) [2021년 06월 15일]
Leetcode - Valid Anagram
문제: LeetCode - 242. Valid Anagram
- 매개변수로 받아오는 문자열들이 같은 문자들로 이루어져있는지 확인하는 문제
코드
const isAnagram = (s, t) => {
if (s.length !== t.length) return false;
const map = new Map();
const nMax = s.length;
let nIdx = 0;
while (nIdx < nMax) {
const sCnt = map.get(s[nIdx]);
isNull(sCnt) ? map.set(s[nIdx], 1) : map.set(s[nIdx], sCnt + 1);
nIdx++;
}
nIdx = 0;
while (nIdx < nMax) {
if (!map.has(t[nIdx])) return false;
map.set(t[nIdx], map.get(t[nIdx]) - 1);
if (map.get(t[nIdx]) < 0) return false;
nIdx++;
}
return true;
};
const isNull = (value) =>
typeof value === 'undefined' || typeof value === 'null';
isAnagram('aacc', 'ccac');
Leetcode - Word Pattern
문제: LeetCode - 290. Word Pattern
- 매개변수 문자열 s가 문자열 pattern과 같은 패턴을 가지고있다면 true
코드
const wordPattern = (pattern, s) => {
const arrS = s.split(' ');
if (arrS.length !== pattern.length) return false;
const map = new Map();
let nIdx = 0;
while (nIdx < pattern.length) {
const currPattern = pattern[nIdx];
if (map.has(currPattern)) {
if (map.get(currPattern) !== arrS[nIdx]) return false;
} else {
const isDifferKeySameValue =
[...map.entries()].findIndex(
([key, value]) =>
key !== currPattern && value === arrS[nIdx],
) > -1;
if (isDifferKeySameValue) return false;
map.set(currPattern, arrS[nIdx]);
}
nIdx++;
}
return true;
};
wordPattern('abba', 'dog dog dog dog');
참고 자료
강의
알고리즘 기초 다지기 프로젝트 (feat. 코드없는 프로그래밍) [2021년 06월 15일]
Leetcode - Valid Anagram
문제: LeetCode - 242. Valid Anagram
코드
Leetcode - Word Pattern
문제: LeetCode - 290. Word Pattern
코드
참고 자료
강의