본문 바로가기

코딩테스트/Coding Bat

[코딩뱃] [자바] Warmup - 2단계 : last2 문제

728x90
728x90

https://codingbat.com/prob/p178318

 

CodingBat Java Warmup-2 last2

Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring).

codingbat.com



= 문제 번역 =

(내가 풀어놓은 설명)

문자열의 제일 뒤쪽 2개의 문자가, 문자의 전체에서 몇 번 반복되는가 count하면 됩니다.

하지만, 문자 길이가 2보다 작으면 0이 반환되어야하며, 반복되어야하는 문자열의 마지막 2개의 문자는 카운트 하지 말아야 합니다. 

 

(직독 직해)

문자열이 주어지면 부분 문자열 길이 2가 문자열과 문자열의 마지막 2개 문자로 나타나는 횟수를 반환하므로 

"hixxxhi"는 1을 반환합니다(끝 부분 문자열은 계산하지 않음).

 

= 문제푸는 팁 =

아래에 있는 표시를 보고, 문제를 풀어야 조금 더 쉽게 해설이 가능 할 것 같다.

 

= 해설 =

< 1 >
public int last2(String str) {
	int len = str.length();
	int count = 0;

	if(len <= 2){
		return 0;
	}

	for(int i = 0; i < len-2; i++){
		String last = str.substring(len-2);
			if(str.substring(i, i+2).equals(last)){
		count++;
		}
	}
return count;
}

< 2 >
public int last2(String str) {
  // Screen out too-short string case.
  if (str.length() < 2) return 0;
  
  String end = str.substring(str.length()-2);
  // Note: substring() with 1 value goes through the end of the string
  int count = 0;
  
  // Check each substring length 2 starting at i
  for (int i=0; i<str.length()-2; i++) {
    String sub = str.substring(i, i+2);
    if (sub.equals(end)) {  // Use .equals() with strings
      count++;
    }
  }

  return count;
}

  return count;
}

처음에는 무슨 번역이랑 문제 자체를 보고 한참 헤메었는데, 우선 solution을 보고, 해설을 보고 어떤 문제인지 분석을 했다. (당황)

이런 경우가 자주 있었던 것은 아니지만, 그래도 문제 번역자체를 보고서 문제가 이해되지 않은 적은 처음이어서 

진짜 많이 당황했지만, 그래도 풀어나갈 수 있었으니까 다행!

728x90