출처: https://school.programmers.co.kr/learn/courses/30/lessons/12903
문제 설명
단어 s의 가운데 글자를 반환하는 함수, solution을 만들어 보세요. 단어의 길이가 짝수라면 가운데 두글자를 반환하면 됩니다.
재한사항
s는 길이가 1 이상, 100이하인 스트링입니다.
입출력 예
s return
"abcde" "c"
"qwer" "w
class Solution {
public String solution(String s) {
String answer = "";
// 단어 s의 가운데 글자를 반환
// 단어의 길이가 짝수라면 가운데 두글자 반환
for(int i = 0; i < s.length(); i++){
if(s.length() % 2 == 0){// 짝수라면 가운데 두글자 반환
answer = s.charAt(s.length() / 2 - 1) + "" + s.charAt(s.length() / 2);
} else {// 홀수라면 가운데 한 글자를 반환
answer = s.charAt(s.length() / 2) + "";// 가운데 인덱스
}
}
return answer;
}
}
단어 길이가 짝수냐 홀수냐로 나눠서
짝수일시 가운데 두글자를
홀수일시 가운데 한글자를 answr배열에 저장후 반환하는 식으로 했다.
다른 사람의 풀이
class StringExercise{
String getMiddle(String word){
return word.substring((word.length()-1)/2, word.length()/2 + 1);
}
// 아래는 테스트로 출력해 보기 위한 코드입니다.
public static void main(String[] args){
StringExercise se = new StringExercise();
System.out.println(se.getMiddle("power"));
}
}
(word.length() - 1) / 2
홀수일 경우 가운데 글자의 인덱스, 짝수일 경우 가운데 두 글자 중 앞 글자의 인덱스
word.length() / 2 + 1
홀수일 경우 가운데 글자의 다음 인덱스, 짝수일 경우 가운데 두 글자 중 뒷 글자의 인덱스 +1
각각 뜻한다.
➡️ substring(start, end)는 start부터 end-1까지 자른다.
➡️ 이 수식은 홀수/짝수를 나누지 않고 한 줄로 해결한 트릭이다.
class StringExercise{
String getMiddle(String word){
int a = word.length();
String word1;
if ( a % 2 == 0 )
word1 = word.substring(a/2 - 1, (a/2) + 1);
else
word1 = word.substring((a/2), (a/2) + 1);
return word1;
}
// 아래는 테스트로 출력해 보기 위한 코드입니다.
public static void main(String[] args){
StringExercise se = new StringExercise();
System.out.println(se.getMiddle("power"));
}
}
class StringExercise{
String getMiddle(String word){
return word != null ? word.substring((word.length()-1)/2,(word.length()+2)/2) : "";
}
// 아래는 테스트로 출력해 보기 위한 코드입니다.
public static void main(String[] args){
StringExercise se = new StringExercise();
System.out.println(se.getMiddle("power"));
System.out.println(se.getMiddle("test1234"));
}
}
삼항 연산자를 쓴 풀이 word != null이면 substring(...) 실행, 아니면 빈 문자열 "" 반환
📌 이해 포인트: substring(start, end)
substring(a, b)는 인덱스 a부터 b-1까지 잘라냄.
즉, 길이가 n일 때 가운데 글자를 고르려면 start, end를 잘 계산해야 함.
✔ 홀수일 때: "power" (길이 5)
word.length() = 5
(5 - 1) / 2 = 4 / 2 = 2 (시작 인덱스)
(5 + 2) / 2 = 7 / 2 = 3 (끝 인덱스)
👉 substring(2, 3) → "w" ✅
✔ 짝수일 때: "test1234" (길이 8)
word.length() = 8
(8 - 1) / 2 = 7 / 2 = 3 (시작 인덱스)
(8 + 2) / 2 = 10 / 2 = 5 (끝 인덱스)
👉 substring(3, 5) → "t1" ✅
| 길이 | 시작 인덱스 (n-1)/2 | 끝 인덱스 (n+2)/2 | 결과 |
|---|---|---|---|
| 5 (홀수) | 2 | 3 | 가운데 1자 ("w") |
| 8 (짝수) | 3 | 5 | 가운데 2자 ("t1") |