본문 바로가기

컴퓨터 프로그래밍/알고리즘

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

(프로그래머스)

문제 설명

문자열 s의 길이가 4 혹은 6이고, 숫자로만 구성돼있는지 확인해주는 함수, solution을 완성하세요. 예를 들어 s가 a234이면 False를 리턴하고 1234라면 True를 리턴하면 됩니다.

제한 사항

  • s는 길이 1 이상, 길이 8 이하인 문자열입니다.

<내 풀이>

	 public static boolean solution(String s) {
	        boolean answer = true;
	      char[] a = s.toCharArray();

	        for(char c : a) {
	        	if ((a.length!=4&&a.length!=6) || (int)c>=65) {
	        		return false;
	        	}
	        }
	                
	        return true;
	    }

<출처:https://coding-factory.tistory.com/74>

참고할만 한 풀이

<남풀이_1>

public boolean solution(String s) {
      if(s.length() == 4 || s.length() == 6){
          try{
              int x = Integer.parseInt(s);
              return true;
          } catch(NumberFormatException e){
              return false;
          }
      }
      else return false;
  }

(나도 이생각은 했었음.....)

 

<남풀이_2>

import java.util.*;

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

(정규표현식을 쓰다니.....)

 

<남풀이_3>

class Solution {
  public boolean solution(String s) {
    return (s.length() != 4 && s.length() != 6) || (s.split("[0-9]").length > 0) ? false:true;
  }
}

(문자 split을 이용해서 할 생각을... 하다니.....아직 많이 부족한 듯 합니다...)