题目描述
编写一个函数,以字符串作为输入,反转该字符串中的元音字母。
左右两侧首先出现的元音字符直接互换,分别第二次出现的元音字符继续互换,以此类推。
示例 1:
输入:leetcode
输出:leotcede
示例 2:
输入:hello
输出:holle
示例 3:
输入:maybe
输出:meyba
算法:reverseVowels()
使用双指针(双撞指针),左指针从头向尾遍历,右指针从尾到头遍历,当两个指针都遍历到元音字符时,交换这两个元音字符。
为了快速判断一个字符是不是元音字符,我们将全部元音字符添加到集合 HashSet<> 中,从而以 O(1) 的时间复杂度进行该操作。
- 时间复杂度为 O(N):所有元素只需要遍历一次
- 空间复杂度 O(1):只需要使用两个额外变量
//将所有元音字符添加到集合HashSet中
private final static HashSet<Character> vowels = new HashSet<>
(Arrays.asList('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'));
public String reverseVowels(String s) {
if (s == null) return null; //判断数组s是否为空
int i = 0, j = s.length() - 1;//定义左右指针
char[] result = new char[s.length()];//new一个字符数组result
while (i <= j) {
char ci = s.charAt(i);//charAt()用于返回指定索引处的字符
char cj = s.charAt(j);
if (!vowels.contains(ci)) {//contains()用于判断字符串中是否包含指定的字符或字符串
result[i++] = ci;
} else if (!vowels.contains(cj)) {
result[j--] = cj;
} else {
result[i++] = cj;
result[j--] = ci;
}
}
return new String(result);
}
算法内容补充
1.charAt()
charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1。
·语法
public char charAt(int index)
·返回值
返回指定索引处的字符。
·实例
//java charAt() 方法
public class Test1 {
public static void main(String args[]) {
String s = "wuarmin";
char result = s.charAt(6);
System.out.println(result);
}
}
//输出结果为:n
2.contains()
contains() 方法用于判断字符串中是否包含指定的字符或字符串
·语法
public boolean contains(CharSequence chars)
·返回值
如果包含指定的字符或字符串返回 true,否则返回 false。
·实例
//java String contains() 方法
public class Test2 {
public static void main(String[] args) {
String myStr = "wuarmin";
System.out.println(myStr.contains("wu"));
System.out.println(myStr.contains("armin"));
System.out.println(myStr.contains("maybe"));
}
}
//输出结果为:
// ture
// ture
// false
注释:写的不好之处请您纠正,新手小白,期待您来指教!!!