Jam's story

[프로그래머스] 문자열 다루기 기본 본문

코딩테스트/프로그래머스

[프로그래머스] 문자열 다루기 기본

애플쩀 2022. 8. 3. 13:10
  • 문자열 길이에서 통과가 되면(문자열길이가 4이거나 6이면)
  • for문으로 문자열을 돌면서, 숫자인지 확인하고, cnt 증가
  • cnt랑 문자열 길이가 같다면 true 아니면 false
class Solution {
    public boolean solution(String s) {
        boolean answer = false;
        int cnt=0;
        if(s.length()==4 || s.length()==6) {
            for(int i=0; i<s.length(); i++){
                if(Character.isDigit(s.charAt(i))){
                    cnt++;
                }
            }
        }
        answer=cnt==s.length()? true: false; 
        return answer;
    }
}

 

다른사람 풀이

import java.util.*;

class Solution {
  public boolean solution(String s) {
        if (s.length() == 4 || s.length() == 6) return s.matches("(^[0-9]*$)");
        return false;
  }
}



import java.util.*;

class Solution {
  public boolean solution(String s) {
        String pattern="^[0-9]*$";
        if (s.length() == 4 || s.length() == 6) return s.matches(pattern);
        return false;
  }
}

 

 

Comments