其他分享
首页 > 其他分享> > Leetcode :345. Reverse Vowels of a String (Easy)

Leetcode :345. Reverse Vowels of a String (Easy)

作者:互联网

反转字符串中的元音字符

  Given s = "leetcode", return "leotcede".

使用双指针指向待反转的两个元音字符,一个指针从头向尾遍历,一个指针从尾到头遍历。

private final static HashSet<Character> vowels = new HashSet<Character>(Arrays.asList('a','e','i','o','u','A','E','I','O','U'));
/*此方法提供了一个创建固定长度的列表的便捷方法,该列表被初始化为包含多个元素: 
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");*/
public String reverseVowels(String s) {
	int i = 0, j = s.length() - 1;
	char[] result = new char[s.length()];
	while(i <= j) {
		char ci = s.charAt(i);
		char cj = s.charAt(j);
		if(!vowels.contains(ci)) {
			result[i++] = ci;
		} else if(!vowels.contains(cj)) {
			result[j--] = cj;
		} else {
			result[i++] = cj;
			result[j--] = ci;
		}
	}
	return new String(result);
}
//in : wasedf
//out: wesadf

 

标签:String,HashSet,Vowels,char,345,length,new,指针
来源: https://blog.csdn.net/chushoufengli/article/details/88195411