Reverse Vowels of a String 仅翻转元音字符

来源:互联网 发布:高程测量记录表的算法 编辑:程序博客网 时间:2024/05/21 04:43

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

这道题跟先前的翻转字符串的唯一区别,就是限制了只能是元音字符。

所以,我们只要增加代码判断首尾字符是不是aeiou  AEIOU。

要注意的问题就是不要让数组越界。

运行时间:


代码:

public class ReverseVowelsofaString {    public String reverseVowels(String s) {        char[] word = s.toCharArray();        int i = 0;        int j = word.length - 1;        while (i < j) {            while (i < j && word[i] != 'a' && word[i] != 'e' && word[i] != 'i' && word[i] != 'o' && word[i] != 'u' && i < j && word[i] != 'A' && word[i] != 'E' && word[i] != 'I' && word[i] != 'O' && word[i] != 'U') {                i++;            }            while (i < j && word[j] != 'a' && word[j] != 'e' && word[j] != 'i' && word[j] != 'o' && word[j] != 'u' && i < j && word[j] != 'A' && word[j] != 'E' && word[j] != 'I' && word[j] != 'O' && word[j] != 'U') {                j--;            }            if (i < j) {                char temp = word[i];                word[i] = word[j];                word[j] = temp;            }            i++;            j--;        }        return new String(word);    }}


1 0