본문 바로가기
Algorithm/Programmers

[Programmers] Lv.0 / 문자열이 몇 번 등장하는지 세기 / Java

by unknownomad 2024. 1. 25.

문제

 

풀이

class Solution {
    public int solution(String myString, String pat) {
        
        int count = 0;
        int pos = myString.indexOf(pat);
        
        while(pos > -1) {
            count++;
            pos = myString.indexOf(pat, pos + 1);
        }
        return count;
    }
}
class Solution {
    public int solution(String myString, String pat) {
        int cnt = 0;
        for(int i = 0; i < myString.length(); i++) {
            if(myString.substring(i).startsWith(pat)) {
                cnt++;
            }
        }
        return cnt;
    }
}

 

  • public String substring(int startIndex)

https://www.programiz.com/java-programming/library/string/substring

 

출처

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

댓글