본문 바로가기

코딩테스트/Coding Bat

[코딩뱃] [자바] Warmup - 1단계 : mixStart 문제

728x90
728x90

https://codingbat.com/prob/p151713

 

CodingBat Java Warmup-1 mixStart

Return true if the given string begins with "mix", except the 'm' can be anything, so "pix", "9ix" .. all count.

codingbat.com



= 문제 번역 =

주어진 문자열이 "mix"로 시작하면 true를 반환합니다. 

단, 'm'은 무엇이든 될 수 있으므로 "pix", "9ix" .. 모두 포함됩니다.

 

= 문제푸는 팁 =

2번 해설과 내가 푼 문제가 크게 다르지는 않은데, if를 두개로 나누었는가, 하나로 묶어서 표현하였는가가 차이이다.

 

= 해설 =

< 1 >
public boolean mixStart(String str) {
  if(str.length()>=3){
  String a = str.substring(1,3);
  return a.equals("ix");
  }else return false;
}

< 2 >
public boolean mixStart(String str) {
  // Check if string is too small
  // (so substring() below does not go off the end)
  if (str.length() < 3) return false;
  
  // Pull out length 2 string for the "ix" part
  // (i.e. substring starting at index 1 and stopping just before 3).
  String two = str.substring(1, 3);
  
  if (two.equals("ix")) {
    return true;
  } else {
    return false;
  }
  // This last part can be shortened to just:
  // return(two.equals("ix"));
}

728x90