๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/์•Œ๊ณ ๋ฆฌ์ฆ˜ ํ’€์ด(Java)

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค_ํฌ๊ธฐ๊ฐ€ ์ž‘์€ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด

by carrot0911 2024. 11. 29.

๋ฌธ์ œ ์„ค๋ช…

https://school.programmers.co.kr/learn/courses/30/lessons/147355

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

SW๊ฐœ๋ฐœ์ž๋ฅผ ์œ„ํ•œ ํ‰๊ฐ€, ๊ต์œก, ์ฑ„์šฉ๊นŒ์ง€ Total Solution์„ ์ œ๊ณตํ•˜๋Š” ๊ฐœ๋ฐœ์ž ์„ฑ์žฅ์„ ์œ„ํ•œ ๋ฒ ์ด์Šค์บ ํ”„

programmers.co.kr

์ˆซ์ž๋กœ ์ด๋ฃจ์–ด์ง„ ๋ฌธ์ž์—ด t์™€ p๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ, t์—์„œ p์™€ ๊ธธ์ด๊ฐ€ ๊ฐ™์€ ๋ถ€๋ถ„๋ฌธ์ž์—ด ์ค‘์—์„œ, ์ด ๋ถ€๋ถ„๋ฌธ์ž์—ด์ด ๋‚˜ํƒ€๋‚ด๋Š” ์ˆ˜๊ฐ€ p๊ฐ€ ๋‚˜ํƒ€๋‚ด๋Š” ์ˆ˜๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ๊ฒƒ์ด ๋‚˜์˜ค๋Š” ํšŸ์ˆ˜๋ฅผ returnํ•˜๋Š” ํ•จ์ˆ˜ solution์„ ์™„์„ฑํ•˜์„ธ์š”.
์˜ˆ๋ฅผ ๋“ค์–ด, t="3141592"์ด๊ณ  p="271" ์ธ ๊ฒฝ์šฐ, t์˜ ๊ธธ์ด๊ฐ€ 3์ธ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์€ 314, 141, 415, 159, 592์ž…๋‹ˆ๋‹ค. ์ด ๋ฌธ์ž์—ด์ด ๋‚˜ํƒ€๋‚ด๋Š” ์ˆ˜ ์ค‘ 271๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ˆ˜๋Š” 141, 159 2๊ฐœ ์ž…๋‹ˆ๋‹ค.

์ œํ•œ ์‚ฌํ•ญ

  • 1 ≤ p์˜ ๊ธธ์ด ≤ 18
  • p์˜ ๊ธธ์ด ≤ t์˜ ๊ธธ์ด ≤ 10,000
  • t์™€ p๋Š” ์ˆซ์ž๋กœ๋งŒ ์ด๋ฃจ์–ด์ง„ ๋ฌธ์ž์—ด์ด๋ฉฐ, 0์œผ๋กœ ์‹œ์ž‘ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ ์˜ˆ

t p result
"3141592" "271" 2
"500220839878" "17" 8
"10203" "15" 3

์ž…์ถœ๋ ฅ ์˜ˆ ์„ค๋ช…

์ž…์ถœ๋ ฅ ์˜ˆ #1

  • ๋ณธ๋ฌธ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ ์˜ˆ #2

  • p์˜ ๊ธธ์ด๊ฐ€ 1์ด๋ฏ€๋กœ t์˜ ๋ถ€๋ถ„๋ฌธ์ž์—ด์€"5", "0", 0", "2", "2", "0", "8", "3", "9", "8", "7", "8"์ด๋ฉฐ ์ด์ค‘ 7๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ˆซ์ž๋Š” "5", "0", "0", "2", "2", "0", "3", "7" ์ด๋ ‡๊ฒŒ 8๊ฐœ๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค.

์ž…์ถœ๋ ฅ ์˜ˆ #3

  • p์˜ ๊ธธ์ด๊ฐ€ 2์ด๋ฏ€๋กœ t์˜ ๋ถ€๋ถ„๋ฌธ์ž์—ด์€ "10", "02", "20", "03"์ด๋ฉฐ, ์ด์ค‘ 15๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์ˆซ์ž๋Š” "10", "02", "03" ์ด๋ ‡๊ฒŒ 3๊ฐœ์ž…๋‹ˆ๋‹ค. "02"์™€ "03"์€ ๊ฐ๊ฐ 2, 3์— ํ•ด๋‹นํ•œ๋‹ค๋Š” ์ ์— ์ฃผ์˜ํ•˜์„ธ์š”.

 

๋‚ด๊ฐ€ ์ž‘์„ฑํ•œ ์ฝ”๋“œ

class Solution {
    public int solution(String t, String p) {
        int answer = 0;

        for (int i = 0; i < t.length()-p.length()+1; i++) {
            String temp = t.substring(i, i+p.length());
            
            if (Long.parseLong(p) >= Long.parseLong(temp)){
                answer++;
            }
        }
        return answer;
    }
}

์ฝ”๋“œ ์„ค๋ช…

  • int answer = 0 : ์กฐ๊ฑด์— ๋งž๋Š” ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์˜ ๊ฐœ์ˆ˜๋ฅผ ์ €์žฅํ•  ๋ณ€์ˆ˜ answer๋ฅผ ์ƒ์„ฑํ•˜๊ณ  0์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•œ๋‹ค.
  • for (int i = 0; i < t.length( )-p.length( )+1; i++) { } : for๋ฌธ์„ ์‚ฌ์šฉํ•ด์„œ i๊ฐ€ 0๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์„œ t์˜ ๊ธธ์ด-p์˜ ๊ธธ์ด+1๋ณด๋‹ค ์ž‘์„ ๋•Œ๊นŒ์ง€ ์ฆ๊ฐ€ํ•œ๋‹ค.
    • String temp = t.substring(i, i+p.length( )) : t์˜ i๋ฒˆ์งธ ์š”์†Œ๋ถ€ํ„ฐ ๊ธธ์ด๊ฐ€ p.length( )์ธ ๋ถ€๋ถ„ ๋ฌธ์ž์—ด์„ ์ถ”์ถœํ•ด์„œ ๋ฌธ์ž์—ด ๋ณ€์ˆ˜ temp์— ์ €์žฅํ•œ๋‹ค.
    • if (Long.parseLong(p) >= Long.parseLong(temp)) { answer++ } : if๋ฌธ์„ ์‚ฌ์šฉํ•ด์„œ p์™€ temp๋ฅผ long ํƒ€์ž…์œผ๋กœ ํ˜•๋ณ€ํ™˜ํ•˜๊ณ  ๊ฐ’์„ ๋น„๊ตํ•œ๋‹ค. p์˜ ๊ฐ’์ด temp์˜ ๊ฐ’๋ณด๋‹ค ํฌ๋‹ค๋ฉด answer๋ฅผ 1 ์ฆ๊ฐ€ํ•œ๋‹ค.