Skip to content

Conversation

@uyeon0
Copy link
Collaborator

@uyeon0 uyeon0 commented Sep 13, 2025

User description

오늘도 멋져요 👍✨


PR Type

Enhancement


Description

  • 리트코드 567번 문제 '문자열 순열' 해결

  • 슬라이딩 윈도우 기법을 사용한 효율적인 구현

  • 알파벳 카운팅 배열과 매칭 카운터를 활용한 최적화


@uyeon0 uyeon0 added the leetcode Leetcode 문제 풀이 label Sep 13, 2025
@uyeon0 uyeon0 merged commit ed02131 into main Sep 13, 2025
8 checks passed
@uyeon0 uyeon0 deleted the upload branch September 13, 2025 15:12
@github-actions
Copy link

PR Reviewer Guide 🔍

🧪 PR contains tests
⚡ Recommended focus areas for review

성능 최적화

matches 변수를 업데이트하는 로직이 불필요하게 복잡합니다. cnt 배열의 값이 0인 경우만 체크하면 되므로, 조건문을 단순화할 수 있습니다. 현재 구현은 O(26n)이지만 O(n)으로 개선 가능합니다.

if (cnt[lIdx] === 0) matches--;
else if (cnt[lIdx] === -1) matches++;
cnt[lIdx] = cnt[lIdx] + 1;

// 오른쪽 문자 하나 더하기
if (cnt[rIdx] === 0) matches--;
else if (cnt[rIdx] === 1) matches++;
cnt[rIdx] = cnt[rIdx] - 1;
엣지케이스 처리

입력 문자열에 알파벳 소문자가 아닌 문자가 포함된 경우나 빈 문자열이 입력된 경우에 대한 처리가 누락되어 있습니다. 예: s1="A1", s2="", s1="", s2="abc" 등의 케이스에서 오류 발생 가능성이 있습니다.

function checkInclusion(s1: string, s2: string): boolean {
  const ALPHA_COUNT = 26;
  if (s1.length > s2.length) return false;
메모리 사용량

cnt 배열을 26 크기로 고정하는 대신 Map을 사용하면 실제 등장하는 문자에 대해서만 카운팅이 가능합니다. 특히 입력 문자열이 적은 종류의 문자로만 구성된 경우 메모리 사용량을 크게 줄일 수 있습니다.

const cnt: number[] = new Array<number>(ALPHA_COUNT).fill(0);

@github-actions
Copy link

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
General
중복 로직을 함수로 추출

문자 카운트 업데이트 로직을 별도의 함수로 추출하면 코드 중복을 줄이고 가독성이 향상됩니다. 왼쪽/오른쪽 문자 처리 로직을 하나의 재사용 가능한 함수로
만드세요.

Leetcode/567.permutation-in-string.ts [37-44]

-// 왼쪽 문자 하나 빼기
-if (cnt[lIdx] === 0) matches--;
-else if (cnt[lIdx] === -1) matches++;
-cnt[lIdx] = cnt[lIdx] + 1;
+function updateMatchCount(cnt: number[], idx: number, isAdding: boolean): number {
+  const oldCount = cnt[idx];
+  const delta = isAdding ? 1 : -1;
+  cnt[idx] += delta;
+  
+  if (oldCount === 0) return -1;
+  if ((isAdding && oldCount === -1) || (!isAdding && oldCount === 1)) return 1;
+  return 0;
+}
 
-// 오른쪽 문자 하나 더하기
-if (cnt[rIdx] === 0) matches--;
-else if (cnt[rIdx] === 1) matches++;
-cnt[rIdx] = cnt[rIdx] - 1;
+// 사용 예:
+matches += updateMatchCount(cnt, lIdx, true);  // 왼쪽 문자 제거
+matches += updateMatchCount(cnt, rIdx, false); // 오른쪽 문자 추가
Suggestion importance[1-10]: 7

__

Why: 반복되는 카운트 업데이트 로직을 함수로 추출하는 것은 코드의 가독성과 유지보수성을 크게 향상시킵니다. updateMatchCount 함수는 복잡한 로직을 잘 캡슐화합니다.

Medium
입력 검증 및 상수 추출

charToIndex 함수를 더 명확하고 안전하게 만들어야 합니다. 입력 문자가 소문자 알파벳인지 검증하고, 상수를 활용하여 가독성을 높이세요.

Leetcode/567.permutation-in-string.ts [4-6]

+const BASE_CHAR_CODE = 'a'.charCodeAt(0);
+
 function charToIndex(c: string): number {
-  return c.charCodeAt(0) - "a".charCodeAt(0);
+  if (!/^[a-z]$/.test(c)) {
+    throw new Error('Input must be a lowercase letter');
+  }
+  return c.charCodeAt(0) - BASE_CHAR_CODE;
 }
Suggestion importance[1-10]: 6

__

Why: 입력 검증과 상수 추출은 코드의 안정성과 가독성을 높이는 좋은 제안이지만, 알고리즘 문제 해결에서는 중요도가 상대적으로 낮습니다. charToIndex 함수는 현재도 충분히 명확합니다.

Low
배열 연산 단순화

reduce 대신 filterlength를 사용하면 코드가 더 명확하고 이해하기 쉬워집니다. 의도를 더 직관적으로 표현할 수 있습니다.

Leetcode/567.permutation-in-string.ts [22-25]

-let matches: number = cnt.reduce(
-  (matches, count) => (count === 0 ? matches + 1 : matches),
-  0
-);
+const matches: number = cnt.filter(count => count === 0).length;
Suggestion importance[1-10]: 5

__

Why: filter().length를 사용하는 방식이 더 읽기 쉽지만, 성능 면에서는 현재의 reduce 구현이 더 효율적입니다. 이는 스타일 선호도의 차이에 가깝습니다.

Low

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

leetcode Leetcode 문제 풀이

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants