Reverse Vowels of a String

来源:互联网 发布:映客刷钻石软件 编辑:程序博客网 时间:2024/06/09 12:40

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

思路:主要是懂得元音是什么,a,e,i,o,u字母,然后就是swap的一个过程,双指针,从前往后,从后往前,分别扫,扫到然后互换即可。

public class Solution {    public String reverseVowels(String s) {        if(s == null) return null;        char[] chars = s.toCharArray();        HashSet<Character> hashset = new HashSet<Character>();        hashset.add('a'); hashset.add('e'); hashset.add('i');hashset.add('o');hashset.add('u');        hashset.add('A'); hashset.add('E'); hashset.add('I');hashset.add('O');hashset.add('U');                int i=0;  int j=chars.length-1;        while( i<j){            if(!hashset.contains(chars[i])){                i++;                continue;            }             if(!hashset.contains(chars[j])){                j--;                continue;            }            char temp = chars[i];            chars[i] = chars[j];            chars[j] = temp;            i++;            j--;        }                return new String(chars);    }}


0 0
原创粉丝点击