345. Reverse Vowels of a String

来源:互联网 发布:网页设计软件 编辑:程序博客网 时间:2024/06/06 04:26

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

Example 1:
Given s = "hello", return "holle".

Example 2:
Given s = "leetcode", return "leotcede".

Note:

The vowels does not include the letter "y".



反转一个字符串里的元音字母。

实现形式上和快排差不多,左右两个指针。还有注意大小写就可以了。

package _345;/** * 345. Reverse Vowels of a String */public class Solution {    private boolean isVowel(char ch) {        char v = Character.toLowerCase(ch);        return v == 'a' || v == 'e' || v == 'i' || v == 'o' || v == 'u';    }    public String reverseVowels(String s) {        int i = 0, j = s.length() - 1;        char[] arr = s.toCharArray();        while (i < j) {            while (i < j && !isVowel(arr[i])) {                i++;            }            while (i < j && !isVowel(arr[j])) {                j--;            }            char temp = arr[i];            arr[i] = arr[j];            arr[j] = temp;            i++;            j--;        }        return new String(arr);    }    public static void main(String[] args) {        Solution solution = new Solution();        System.out.println(solution.reverseVowels("wwww"));    }}

原创粉丝点击