leetcode 1704, Determine if String Halves Are Alike

NJW·2022년 12월 2일
0

코테

목록 보기
119/170

들어가는 말

길이가 짝수인 문자열이 주어졌을 때, 절반을 나눠서 소문자 모음과 대문자 모음의 갯수를 세준다. 만일 그 갯수가 같다면 true를 아니면 flase를 반환한다.

코드 설명

  1. 문자를 두 개로 나눠준다(아니면 절반 인덱스를 찾아서 바로 반복문을 돌려줄 수도 있음).
        String a = s.substring(0, s.length()/2);
        String b = s.substring(s.length()/2);
  1. hashset에 찾고자 하는 문자들을 넣어준다.
        HashSet<Character> hashset = new HashSet<>();
        hashset.add('a');
        hashset.add('e');
        hashset.add('i');
        hashset.add('o');
        hashset.add('u');
        hashset.add('A');
        hashset.add('E');
        hashset.add('I');
        hashset.add('O');
        hashset.add('U');
  1. 나눈 문자에서 hashset에 들어간 문자가 잇는지 확인한다.
        for(int i=0; i<a.length(); i++){
            if(hashset.contains(a.charAt(i))){
                countA++;
            }
            if(hashset.contains(b.charAt(i))){
                countB++;
            }

        }
  1. 두 개의 갯수를 비교해서 true와 false를 반환한다.
        return countA == countB;

전체 코드

class Solution {
    public boolean halvesAreAlike(String s) {
        String a = s.substring(0, s.length()/2);
        String b = s.substring(s.length()/2);
        int countA = 0;
        int countB = 0;

        HashSet<Character> hashset = new HashSet<>();
        hashset.add('a');
        hashset.add('e');
        hashset.add('i');
        hashset.add('o');
        hashset.add('u');
        hashset.add('A');
        hashset.add('E');
        hashset.add('I');
        hashset.add('O');
        hashset.add('U');

        for(int i=0; i<a.length(); i++){
            if(hashset.contains(a.charAt(i))){
                countA++;
            }
            if(hashset.contains(b.charAt(i))){
                countB++;
            }

        }

        return countA == countB;
    }
}

여담

HashSet을 사용하지 않는 방법도 있다. 바로 String의 indexOf 기능을 사용하는 것. 찾고자 하는 문자를 String으로 만든 해당 문자열에 a문자열의 문자가 존재하면 즉, view.indexOf(c)의 값이 -1이 아니라면 숫자를 ++해준다. 여기서 -1의 의미는 view에 문자 c가 존재하지 않는다는 걸 의미한다.

링크

https://leetcode.com/problems/determine-if-string-halves-are-alike/description/

profile
https://jiwonna52.tistory.com/

0개의 댓글