Quiz Link:
프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
/*
* Objective:
* Count substrings of t (with the same length as p) whose numeric value is
* less than or equal to p's numeric value.
*
* Strategy:
* Parse both strings as long rather than BigInteger.
*
* Rationale:
* The problem guarantees p's length is at most 18 digits.
* Since long can hold up to 19 digits (Long.MAX_VALUE ≈ 9.2 × 10^18),
* parsing an 18-digit string as long is always safe — no overflow risk.
* This avoids the overhead of BigInteger while remaining correct.
*
* Approach:
* 1. Parse p into a long value once, outside the loop.
* 2. Slide a window of length p across t, one character at a time.
* 3. Parse each window substring into a long.
* 4. If the window value is less than or equal to p's value, increment the counter.
* 5. Repeat until the window's right edge reaches the end of t.
*/
class Solution {
public int solution(String t, String p) {
int answer = 0;
int pLength = p.length();
long pValue = Long.parseLong(p);
for (int i = 0; i <= t.length() - pLength; i++) {
long tValue = Long.parseLong(t.substring(i, i + pLength));
if (tValue <= pValue) {
answer++;
}
}
return answer;
}
}'Algorithm' 카테고리의 다른 글
| [Algorithm] Modular Arithmetic - Caesar Cipher (0) | 2026.02.23 |
|---|---|
| [Algorithm] Exhaustive Search - Business Card Wallet sample case (0) | 2026.02.21 |
| [알고리즘] 크기가 작은 부분 문자열 (0) | 2026.02.20 |
| [알고리즘] 이상한 문자 만들기 - 향상된 for문의 함정과 String 성능 이슈 (0) | 2026.02.13 |
| [알고리즘] 직사각형 별찍기 (0) | 2026.02.06 |