본문 바로가기

코딩테스트/Coding Bat

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

728x90
728x90

https://codingbat.com/prob/p101475

 

CodingBat Java Warmup-2 frontTimes

Given a string and a non-negative int n, we'll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front;frontTimes("Chocolate", 2) → "ChoCho"frontTimes("Chocolate", 3)

codingbat.com



= 문제 번역 =

(1) 문자열과 음수가 아닌 int n이 주어진다면,

(2) 문자열의 앞부분이 처음 3개 문자 또는 문자열이 길이 3보다 작은 경우는 모든 문자열들을

(3) 앞에서부터 문자열을 n번 반복한 문자열을 반환합니다.

 

= 문제푸는 팁 =

stringTimes 문제와 기본적인 문제 풀이는 같지만,

문자열이 3보다 작을 때는 그 전부의 문자열을 n번 가져와야하는 것이 문제 풀이의 포인트이다.

처음에는 int 3보다 작을 때, 어떻게 조건을 설정해야 문자열 전체를 가져올까 고민했는데...

3을 미지수로 둔 후에, 문자열이 3보다 작을 때, 문자열 자체를 str.length()로 가져오면 해결되는 문제였다.

 

= 해설 =

public String frontTimes(String str, int n) {
	int fl = 3;
	String result = "";

	if(fl>str.length()){
  		fl=str.length();
		}
	
	String front = str.substring(0,fl);
	for(int i=0;i<n;i++){
    	result+=front;
		}
	return result;
}

728x90