Algorithm

[Algorithm] Applying Sliding Window pattern

montmer27 2026. 2. 20. 13:33

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;
    }
}