zoukankan      html  css  js  c++  java
  • 345. Reverse Vowels of a String【Easy】【双指针-反转字符串中的元音字符】

    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".

    Accepted
    142,249
    Submissions
    348,669
     
    import java.util.Arrays;
    import java.util.HashSet;
    
    class Solution {
        
        private final static HashSet<Character> vowels = 
                new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
        public String reverseVowels(String s) {
            int len = s.length();
            int i = 0, j = len - 1;
            char[] result = new char[s.length()];
            while(i <= j) {
                char ci = s.charAt(i);
                char cj = s.charAt(j);
                if(!vowels.contains(ci)) {
                    result[i++] = ci;
                } else if(!vowels.contains(cj)) {
                    result[j--] = cj;
                } else {
                    result[i++] = cj;
                    result[j--] = ci;
                }
            }
            return new String(result); //
        }
        
    }

    import java.util.Arrays;
    import java.util.HashSet;
    
    class Solution {
        public String reverseVowels(String s) {
            if(s == null || s.length() == 0) return s;
            int i = 0, j = s.length() - 1;
            char[] str = s.toCharArray();
            while(i < j) {
                if(isVolwe(str[i]) && isVolwe(str[j])) {
                    char tmp = str[i];
                    str[i] = str[j];
                    str[j] = tmp;
                    i++;
                    j--;
                }
                else if(!isVolwe(str[i])) {
                    i++;
                } else {
                    j--;
                }
            }
            return new String(str);
        }
        private boolean isVolwe(char ch) {
            ch = Character.toLowerCase(ch);
            return ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'; 
        }
    }

  • 相关阅读:
    微服务简介
    Apache httpd.conf
    搭建PHP开发环境
    搭建Apache开发环境
    Swift 项目编译优化(一)
    用Flutter 写一个简单页面
    Sign In With Apple(一)(转)
    Xcode DeviceSupport
    MQTT初始篇笔记整理
    UITableView使用过程中可能遇到的问题
  • 原文地址:https://www.cnblogs.com/Roni-i/p/10426923.html
Copyright © 2011-2022 走看看