目录

题目
Write a function that takes a string as input and reverse only the vowels of a string.
Example:
Given s = “hello”, return “holle”.
Given s = “leetcode”, return “leotcede”.
Note:
The vowels does not include the letter “y”.
解决方案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| public class Solution { public String reverseVowels(String s) { int N = s.length(); if(s == null || N == 0) return ""; StringBuilder builderVowel = new StringBuilder(); for(int i = 0; i < N; i++){ if(isVowel(s.charAt(i))){ builderVowel.append(s.charAt(i)); } } int k = builderVowel.length()-1; StringBuilder builder = new StringBuilder(); for(int i = 0; i < N; i++){ if(!isVowel(s.charAt(i))){ builder.append(s.charAt(i)); } else { builder.append(builderVowel.charAt(k)); k--; } } return builder.toString(); } private static boolean isVowel(char input){ if('a' == input || 'e' == input || 'i' == input || 'o' == input || 'u' == input || 'A' == input || 'E' == input || 'I' == input || 'O' == input || 'U' == input){ return true; } else { return false; } } }
|
注意事项
- 元音字母为a,e,i,o,u,同时要考虑到大写。
- 第一次遍历找到所有元音字母并按顺序保存到一个builderVowel中。第二次遍历,如果当前为不是原因,直接添加到结果builder中,如果当前位是元音字母,则从builderVowel尾部取出一个字符添加到builder中。