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);
        }
    }
  • 相关阅读:
    多线程(6)线程属性
    多线程(五) Thread和Object中线程相关方法
    面试汇总
    多线程(4)线程生命周期
    多线程(3) 多线程之线程的停止和中断
    springboot(6)redis缓存
    软件安装(总)
    redis分布式锁
    第一天
    Thinkphp5高级进阶教程
  • 原文地址:https://www.cnblogs.com/fatttcat/p/11338935.html
Copyright © 2011-2022 走看看