[LeetCode][JAVA] 345. Reverse Vowels of a String

탱귤생귤·2023년 12월 13일
0

LeetCode

목록 보기
5/16

I used 2 array lists, one for index and the other for vowel char.

class Solution {
    public String reverseVowels(String s) {
        List<Integer> listForIdx = new ArrayList<>();
        List<Character> listForChar = new ArrayList<>();

        StringBuilder sb = new StringBuilder(s);

        for (int i = 0; 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'
                    || s.charAt(i) =='A' || s.charAt(i) =='E' || s.charAt(i) =='I' ||s.charAt(i) == 'O' || s.charAt(i) =='U') {
                listForIdx.add(i);
                listForChar.add(s.charAt(i));
            }
        }//for

        //reverse the list of char
        Collections.reverse(listForChar);

        for (int i = 0; i < listForIdx.size(); i++) {
            int idx = listForIdx.get(i);
            sb.replace(idx, idx+1, listForChar.get(i).toString());
        }

       return sb.toString();
        
    }
}

I studied with other codes. This code uses two pointers. The part I liked was using indexOf().

class Solution {
    public String reverseVowels(String s) {
       char[] word = s.toCharArray();
        String vowels = "aeiouAEIOU";
        int start = 0;
        int end = s.length() - 1;

        while (start < end) {
            //when the start pointer points vowel
            if (vowels.indexOf(word[start]) == -1) {
                start++;
            }

            //when the end pointer points vowel
            if (vowels.indexOf(word[end]) == -1) {
                end--;
            }

            if (start < end && vowels.indexOf(word[start]) != -1 && vowels.indexOf(word[end]) != -1) {
                char tmp = word[start];
                word[start] = word[end];
                word[end] = tmp;
                start++;
                end--;
            }

        }

        String ans = new String(word);
       return ans;
        
    }
}

0개의 댓글