5ms Java Two pointer solution


  • 5
    S
    public class Solution {
        public String reverseVowels(String s) {
            if (s == null) {
                throw new IllegalArgumentException();
            }
            if (s.length() <= 1) {
                return s;
            }
            char[] str = s.toCharArray();
            for (int i = 0, j = str.length - 1; i < j; i++, j--) {
                while (i < j && !isVowel(str[i])) i++;
                while (i < j && !isVowel(str[j])) j--;
                if (i <= j) swap(str, i, j);
            }
            return new String(str);
        }
        private boolean isVowel(char ch) {
            char c = Character.toLowerCase(ch);
            return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
        }
        private void swap(char[] str, int i, int j) {
            char tmp = str[i];
            str[i] = str[j];
            str[j] = tmp;
        }
    }

  • 0
    T

    Your code almost breaks in Turkey ;) Try running:

    public static void main(String[] args) {
    	Locale.setDefault(Locale.forLanguageTag("tr-TR"));
    	System.out.println("I don't care about localization.".toLowerCase());
    	System.out.println("I don't care about localization.".toUpperCase());
    }
    

    Luckily for you the static method in Character is not affected by this weirdness.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.