문제설명>
단어 s의 가운데 글자를 반환하는 함수, solution을 만들어 보세요. 단어의 길이가 짝수라면 가운데 두글자를 반환하면 됩니다.재한사항
- s는 길이가 1 이상, 100이하인 스트링입니다.
코드>
스트링을 한 글자씩 split했다.
길이를 구해서 t 변수에 담는다.
짝수/홀수를 구분해서 스트링변수 answer에 담는다.
class Solution {
public String solution(String s) {
String answer = "";
String[] s2 = s.split("");
int t = s.length();
for(int i=0;i<t;i++){
if(t%2==0) {
if(i==(t/2)-1) answer = s2[i];
if(i==t/2) answer+= s2[i];
}
else {
if(i==t/2) answer = s2[i];
}
}
return answer;
}
}
리뷰>
String answer = "" 를 지우고,
스트링의 길이를 구해서 홀수면 toString(s.charAt(ans/2))로 그대로 반환
s.charAt() //returns the character at the specified index in a string.
Character.toString //char를 String으로 바꾼다.
//다른 사람의 풀이
class Solution {
public String solution(String s) {
int ans = s.length();
if (ans % 2 == 1){
return Character.toString(s.charAt(ans/2));
}
else{
return s.substring(ans/2-1, ans/2+1);
}
}
}
'코딩테스트 연습 > JAVA' 카테고리의 다른 글
[프로그래머스] 문자열 다루기 기본 (0) | 2020.02.25 |
---|---|
[프로그래머스] K번째 수 (0) | 2020.02.04 |
[프로그래머스] 문자열 내 p와 y의 개수 (0) | 2020.01.30 |
댓글