bobo老师, 我用了2种解法, 但是leetcode 给出的运行性能报告和预期的不太符合, 下面是我的分析,还请老师指点下
class Solution {
public String reverseVowels(String s) {
char[] vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
int l = 0, r = s.length() - 1;
char[] sCharArray = s.toCharArray();
while (l < r) {
boolean left = isVowel(vowels, s.charAt(l));
boolean right = isVowel(vowels, s.charAt(r));
if (left && right) {
char temp = sCharArray[l];
sCharArray[l++] = sCharArray[r];
sCharArray[r--] = temp;
}
if (!left) {
l++;
}
if (!right) {
r--;
}
}
return String.valueOf(sCharArray);
}
private boolean isVowel(char[] vowels, char value) {
for (int i = 0; i < vowels.length; i++) {
if (vowels[i] == value) {
return true;
}
}
return false;
}
}
class Solution {
public String reverseVowels(String s) {
Set<Character> charSet = new TreeSet<>();
charSet.add('a');
charSet.add('e');
charSet.add('i');
charSet.add('o');
charSet.add('u');
charSet.add('A');
charSet.add('E');
charSet.add('I');
charSet.add('O');
charSet.add('U');
int l = 0, r = s.length() - 1;
char[] sCharArray = s.toCharArray();
while (l < r) {
boolean left = isVowel(charSet, s.charAt(l));
boolean right = isVowel(charSet, s.charAt(r));
if (left && right) {
char temp = sCharArray[l];
sCharArray[l++] = sCharArray[r];
sCharArray[r--] = temp;
}
if (!left) {
l++;
}
if (!right) {
r--;
}
}
return String.valueOf(sCharArray);
}
private boolean isVowel(Set<Character> characters, char value) {
return characters.contains(value);
}
}
isVowel()
方法在查找是否属于元音字母时, 是从 0 开始遍历 元音字符集, 所以我认为这里应该是比 用 Set<> 慢的contains
方法是基于红黑树的查找, 按理要比从 0 index 遍历要快的?登录后可查看更多问答,登录/注册