Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- leedcode
- 알고리즘스터디
- React useMemo 사용법
- React useEffect 안티패턴
- 스쿼드조직
- RxJS 오퍼레이터
- React hooks 남용 사례
- 개발자커뮤니케이션
- React 리렌더링 최적화
- Blind75
- RxJS 결합 오퍼레이터
- 달래스터디
- RxJS 마블 다이어그램
- React 성능 최적화 방법
- 자바스크립트 고차 함수 vs Observable
- contains duplicate
- Observable vs Array
- useCallback 성능 최적화
- RxJS 변환 오퍼레이터
- RxJS 멀티캐스팅
- React useCallback 사용법
- 알고리즘
- RxJS 에러 처리
- RxJS 함수형 프로그래밍
- useMemo 성능 최적화
- leetcode
- 협업문화
- Climbing Stairs
- RxJS 생성 오퍼레이터
- DaleStudy
Archives
- Today
- Total
수쿵의 IT월드
DaleStudy | Leetcode Study 2주차 - Valid Anagram 본문

문제
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Constraints:
- 1 <= s.length, t.length <= 5 * 10^5
sandtconsist of lowercase English letters.
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
풀이
t가 s의 애너그램이라면, true를 리턴하고 아니라면 false를 리턴하면 되는 문제이다. 즉, s를 재배열해서 t를 만들 수 있다면 true를 리턴하면 된다. 이 문제는 객체에 각각 나온 수를 비교하는 방법과 자바스크립트 sort 함수를 이용해서 푸는 방법이 있는데, 가장 손쉽게 할 수 있는 방법은 sort함수를 이용하는 것이다.
function isAnagram(s: string, t: string): boolean {
return s.split('').sort().join() === t.split('').sort().join()
};
하지만 이렇게 풀면, 배열로 변경했다가 다시 문자열로 변경해야하는 작업이 있어 시간복잡도에서는 좋은 점수를 받지 못할 수 있다.
객체를 이용해서 하는 방법은, 하나의 문자열을 객체로 변환한 후, 다른 문자열을 루프를 돌려 그 문자열이 존재하는지 안하는지를 객체에서 확인하면 된다.
function isAnagram(s: string, t: string): boolean {
if (s.length !== t.length) return false;
const objS: {[key: string]: number;} = {};
for (const str of s) {
objS[str] = (objS[str] ?? 0) + 1
}
for (const str of t) {
if (!objS[str]) { return false; }
objS[str]--;
}
return true;
}
Link: https://leetcode.com/problems/valid-anagram/description/