본문 바로가기

코딩테스트/Coding Bat

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

728x90
728x90

https://codingbat.com/prob/p194667

 

CodingBat Java Warmup-2 countXX

Count the number of "xx" in the given string. We'll say that overlapping is allowed, so "xxx" contains 2 "xx".

codingbat.com



= 문제 번역 =

주어진 문자열에서 "xx"의 수를 센다. 겹침이 허용되므로 "xxx"에는 2개의 "xx"가 포함됩니다.

 

= 문제푸는 팁 =

우선 이 문제를 풀 때 알아야 할 건, xx를 하나로 생각하기 때문에, for구문을 돌릴 때, str.length()-1까지 int i 가 돌아야 한다.

그리고, substring을 할 때는, 까먹지 말아야할게 substring(a,b)할 때 실제로 가져오는 문자 값이 b-1까지 가져오는거니까

그것 까지 생각하고 for구문 돌리는거 까먹지 말기~ substring을 (i, i+2)로 돌려야한다. 까먹지말기!

 

= 해설 =

< 1 >
int countXX(String str) {
	int count = 0;
	for(int i=0; i<str.length()-1; i++) {
		if(str.charAt(i)=='x'&&str.charAt(i+1)=='x'){
		count++;
		}
	}
	return count;
}

< 2 >
int countXX(String str) {
	int count = 0;
	for (int i = 0; i < str.length()-1; i++) {
		if (str.substring(i, i+2).equals("xx")) count++;
	}
	return count;
}

// Solution notes: the loop is shortened to end at str.length()-1
// so we can pull out a length 2 substring without going out of bounds.
// Remember to use equals() to compare strings, not ==.

728x90