zoukankan      html  css  js  c++  java
  • 345. Reverse Vowels of a String

    Write a function that takes a string as input and reverse only the vowels of a string.

    Example 1:

    Input: "hello"
    Output: "holle"
    

    Example 2:

    Input: "leetcode"
    Output: "leotcede"

    Note:
    The vowels does not include the letter "y".

    use two pointers

    naive solution:

    class Solution {
        public String reverseVowels(String s) {
            Set<Character> set = new HashSet<>();
            set.add('A');
            set.add('E');
            set.add('I');
            set.add('O');
            set.add('U');
            set.add('a');
            set.add('e');
            set.add('i');
            set.add('o');
            set.add('u');
            
            char[] c = s.toCharArray();
            int i = 0, j = c.length - 1;
            while(i < j) {
                if(set.contains(c[i]) && set.contains(c[j])) {
                    swap(c, i++, j--);
                } else if(set.contains(c[i])) {
                    j--;
                } else if(set.contains(c[j])) {
                    i++;
                } else {
                    i++;
                    j--;
                }
            }
            return new String(c);
        }
        
        private void swap(char[] c, int i, int j) {
            char tmp = c[i];
            c[i] = c[j];
            c[j] = tmp;
        }
    }

    optimized

    class Solution {
        public String reverseVowels(String s) {
            Set<Character> set = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
            
            char[] c = s.toCharArray();
            int i = 0, j = c.length - 1;
            while(i < j) {
                while(i < j && !set.contains(c[i])) {
                    i++;
                }
                while(i < j && !set.contains(c[j])) {
                    j--;
                }
                char tmp = c[i];
                c[i] = c[j];
                c[j] = tmp;
                
                i++;
                j--;
            }
            return new String(c);
        }
    }
  • 相关阅读:
    台州 OJ 3847 Mowing the Lawn 线性DP 单调队列
    洛谷 OJ P1417 烹调方案 01背包
    快速幂取模
    台州 OJ 2649 More is better 并查集
    UVa 1640
    UVa 11971
    UVa 10900
    UVa 11346
    UVa 10288
    UVa 1639
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11338935.html
Copyright © 2011-2022 走看看