【LeetCode】 345. Reverse Vowels of a String

来源:互联网 发布:如何自学数控编程 编辑:程序博客网 时间:2024/05/17 17:44

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

public class Solution {    public String reverseVowels(String s) {        if (s == null || s.length() == 0) {            return s;        }        HashSet<Character> hs = new HashSet<Character>(10);        hs.add('a');        hs.add('i');        hs.add('e');        hs.add('o');        hs.add('u');        hs.add('A');        hs.add('U');        hs.add('I');        hs.add('E');        hs.add('O');        char[] charArray = s.toCharArray();        int start = 0, end = s.length() - 1;        while (start < end) {            while (start < end && !hs.contains(charArray[start])) {                start++;            }            while (start < end && !hs.contains(charArray[end])) {                end--;            }            char temp = charArray[start];            charArray[start] = charArray[end];            charArray[end] = temp;            start++;            end--;        }        return new String(charArray);    }}


0 0
原创粉丝点击