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

[Codewars] Exes and Ohs

by 줍 2024. 6. 10.

Q. Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contain any char.

 

Examples input/output:

XO("ooxx") => true

XO("xooxx") => false

XO("ooxXm") => true

XO("zpzpzpp") => true // when no 'x' and 'o' is present should return true

XO("zzoo") => false

 

S. 간단하게 쓰려고 forEach와 삼항연산자를 이용했는데 가독성면에서는 좋지 않은 것 같다

bool XO(String str) {
  int o = 0;
  int x = 0;
  str.toLowerCase().split('').forEach((e) => e == 'o' ? o += 1 : e == 'x' ? x += 1 : 0);
  return o == x ? true : false;
}

 

+

allMatches가 또 나왔다. 다트에선 문자열을 잘 다루려면 역시 정규표현식을 잘 알아야하는 것 같다. 또 문자열 문제나오면 써봐야겠댱

bool XO(String str) {
  final s = str.toLowerCase();
  return 'o'.allMatches(s).length == 'x'.allMatches(s).length;
}

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

[Codewars] Tribonacci Sequence  (0) 2024.06.11
[Codewars] Counting Duplicates  (0) 2024.06.10
[Codewars] Create Phone Number  (0) 2024.06.09
[Codewars] Find The Parity Outlier  (1) 2024.06.09
[Codewars] You're a square!  (0) 2024.06.09