문자열 내 p와 y의 개수

J·2021년 3월 18일
0

코딩테스트 연습

목록 보기
9/28

string으로 비교

import java.util.*;

class Solution {
    boolean solution(String s) {
        boolean answer = true;
    
        int a = 0;
        int b = 0;
        
        for(int i=0;i<s.length();i++) {
            String x = s.substring(i,i+1);
            if(x.compareToIgnoreCase("p")==0) a++;
            if(x.compareToIgnoreCase("y")==0) b++;
        }
        if(a==b) answer = true;
        else answer = false;
        
        return answer;
    }
}

char로 비교

증감을 이용해 count 하나로만 사용한 방법

class Solution {
    boolean solution(String s) {
        s = s.toLowerCase(); 
        int count = 0;

        for (int i = 0; i < s.length(); i++) {

            if (s.charAt(i) == 'p')
                count++;
            else if (s.charAt(i) == 'y')
                count--;
        }

        if (count == 0)
            return true;
        else
            return false;
    }
}

0개의 댓글