116.Reverse Vowels of a String

来源:互联网 发布:永硕网盘源码 编辑:程序博客网 时间:2024/05/29 09:37

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

Subscribe to see which companies asked this question

分析: 给定一个字符串,只把字符串中的元字符转置。
  定义两个下标i和j,i自增直到遇到元音字符,j自减直到遇到元音字符。
  结束循环的条件是i>=j.

/*初始化好保存元音字符的集合*/Set<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');}/**@author  * 给定一个字符串,只把字符串中的元字符转置。 * 定义两个下标i和j,i自增直到遇到元音字符,j自减直到遇到元音字符。 * 结束循环的条件是i>=j. * @date 20160423 * @param s * @return */public String reverseVowels(String s) {char[] arr = s.toCharArray();int  len = s.length();if(len<=1){return s;}char temp;int i=0;int j=len-1;while(i<j){/*i自增直到遇到元音字符*/while(i<j && !hashset.contains(arr[i])){i++;}/*j自减直到遇到元音字符*/while(i<j && !hashset.contains(arr[j])){j--;}if(i>=j){return new String(arr);}else{temp = arr[i];arr[i] = arr[j];arr[j] = temp;i++;j--;}}return new String(arr);    }

0 0
原创粉丝点击