코린이의 소소한 공부노트

[LeetCode/Easy] 1704. Determine if String Halves Are Alike 본문

코딩테스트 풀이/JAVA

[LeetCode/Easy] 1704. Determine if String Halves Are Alike

무지맘 2023. 1. 2. 13:47

1. Input

1) 문자열 s

 

2. Output

1) s를 반으로 나눴을 때, 나눈 두 문자열이 alike하면 true, 다르면 false를 반환

- 문자열이 alike하다는 것은 각 문자열에 있는 모음의 수가 같다는 것을 의미한다.

 

3. Constraint

1) 2 <= s.length <= 1000

2) s.length%2==0

3) s는 영어 대소문자로 이루어져 있다.

 

4. Example

Input: s = "book" -> Output: true (bo / ok)

Input: s = "textbook" -> Output: false (text / book)

 

5. Code

1) 첫 코드(2022/06/10)

s = s.toLowerCase();
int count = 0;

// a의 모음 개수 세기
for(int i=0 ; i<s.length()/2 ; i++)
    if(s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i' || s.charAt(i) == 'o' || s.charAt(i) == 'u')
        count++;

// b의 모음 개수 세기
for(int i=s.length()/2 ; i<s.length() ; i++)
    if(s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i' || s.charAt(i) == 'o' || s.charAt(i) == 'u')
        count--;

return count==0 ? true : false;

2) 길이를 줄여본 코드(2023/01/02)

s = s.toLowerCase();
return s.substring(0, s.length()/2).replaceAll("[aeiou]","").length()
    == s.substring(s.length()/2, s.length()).replaceAll("[aeiou]","").length();

  - 실행시간은 차이가 없고, 메모리는 더 먹었다. 문자열 연산을 안하는 방향으로 가는게 맞는듯하다.