본문 바로가기
알고리즘/Codewars

[Codewars] Get the Middle Character

by 줍 2024. 6. 4.

Q. You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters.

 

#Examples:

Kata.getMiddle("test") should return "es"

Kata.getMiddle("testing") should return "t"

Kata.getMiddle("middle") should return "dd"

Kata.getMiddle("A") should return "A"

 

#Input

A word (string) of length 0 < str < 1000 (In javascript you may get slightly more than 1000 in some test cases due to an error in the test cases). You do not need to test for this. This is only here to tell you that you do not need to worry about your solution timing out.

 

#Output

The middle character(s) of the word represented as a string.

 

S. 스위프트의 문자열처럼 정수 인덱스로 조회를 못할거라고 생각해서 List로 바꿔주고 > 요소 조회 후 > 다시 문자열로 만들어주었다.

String getMiddle(String s) {
  final int middle = s.length ~/ 2;
  if (s.length.isOdd) {    
    return s.split('')[middle];
  } else {
    return s.split('').sublist(middle - 1, middle + 1).join('');
  }
}

 

+

다트에서는 문자열도 정수 인덱스로 조회가 가능하다. 따라서 아래처럼 작성할 수 있다.

범위를 지정해 sublist, subString을 얻을 수 있으며 (a, b)는 [a..<b]를 의미한다.

String getMiddle(String s) {
  final int middle = s.length ~/ 2;
  return s.length.isOdd ? s[middle] : s.subString(middle - 1, middle + 1);
}

'알고리즘 > Codewars' 카테고리의 다른 글

[Codewars] Multiples of 3 or 5  (0) 2024.06.06
[Codewars] Mumbling  (0) 2024.06.04
[Codewars] Sum of positive  (1) 2024.06.03
[Codewars] Return Negative  (0) 2024.06.03
[Codewars] Descending Order  (0) 2024.06.03