Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = "hello", return "holle".
Given s = "hello", return "holle".
Example 2:
Given s = "leetcode", return "leotcede".
Solution:Given s = "leetcode", return "leotcede".
Just use two point from start and end of the string, respectively.
BE CAREFUL ABOUT THE UPPER CASE!
Code(Java):
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 32 33 34 35 36 37 38 39 40 41 | public class Solution { public String reverseVowels(String s) { if (s == null || s.length() == 0 ) { return "" ; } char [] cs = s.toCharArray(); int start = 0 ; int end = cs.length - 1 ; while (start < end) { while (start < end && !isVowel(cs[start])) { start++; } while (start < end && !isVowel(cs[end])) { end--; } if (start < end) { swap(cs, start, end); start++; end--; } } return new String(cs); } private boolean isVowel( char b) { char c = Character.toLowerCase(b); return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ; } private void swap( char [] cs, int start, int end) { char temp = cs[start]; cs[start] = cs[end]; cs[end] = temp; } } |
No comments:
Post a Comment