크기가 작은 부분문자열 (자바)

김재현·2023년 11월 14일
0

알고리즘 풀이

목록 보기
15/89
post-thumbnail

문제

정답 코드1

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

        double pInt = Double.parseDouble(p);

        for (int i = 0; i < t.length() - p.length() + 1; i++) {
            String tempString = "";
            for (int j = 0; j < p.length(); j++) {
                tempString += t.charAt(i + j);
                System.out.println(tempString);
            }

            if (Double.parseDouble(tempString) <= pInt) {
                answer++;
            }
        }
        return answer;
    }

그 과정

  • 정신줄 놓고 있다가 t.length(), p.lenth()에서 까딱하면 범위 넘어버리거나 부족하겠어서 +1 해줬다.

  • 오늘도 .valueOf 를 쓰려다가 오류가 나서.... 찾아보니 parse 라는 멋진게 있더라! 바로 사용.

  • 처음에 int로 주고 Integer.parseInteger() 로 풀었는데, 런타임 오류.
    --> 생각해보니 10000자리수면 int를 넘어가잖아..? long으로 해도 되겠지만 double로 해버렸다.
    (double도 정확도 주의해서 써야 할 것 같다 -> 좀 더 공부해보자)

정답 코드2

    public int sss(String t, String p) {
        int answer = 0;

        for(int i=0;i<t.length()-p.length()+1;i++) {
            if(Double.parseDouble(t.substring(i,i+p.length()))<=Double.parseDouble(p)) {
                answer++;
            }
        }

        return answer;
    }

substring 메서드 쓰는 문제였구나

이런 기능이 있다는걸 잊고 있었다.
사용해서 다시 풀어봤다. 깔끔하고 뿌듯했다.

profile
I live in Seoul, Korea, Handsome

0개의 댓글