Write code to reverse vowels o | CareerCup
就是说将一句话里面所有的元音倒序, 比如说 fine 要变成 feni
X. swap vowels by comparing leftmost and right most vowel in the string, then compare next leftmost and right most vowel and swap, continue until reach the middle of the string.
Read full article from Write code to reverse vowels o | CareerCup
就是说将一句话里面所有的元音倒序, 比如说 fine 要变成 feni
X. swap vowels by comparing leftmost and right most vowel in the string, then compare next leftmost and right most vowel and swap, continue until reach the middle of the string.
public static void main(String[] args) {
System.out.println(sentence);
char[] letters = sentence.toCharArray();
int left = 0;
int right = letters.length - 1;
char temp;
boolean left_visit = false;
boolean right_visit = false;
for (int i = 0; i < letters.length; i++) {
if (letters[left] == 'a' || letters[left] == 'e' || letters[left] == 'i' || letters[left] == 'o'
|| letters[left] == 'u') {
left_visit = true;
} else {
if (left_visit == false) {
left++;
}
}
if (letters[right] == 'a' || letters[right] == 'e' || letters[right] == 'i' || letters[right] == 'o'
|| letters[right] == 'u') {
right_visit = true;
} else {
if (right_visit == false) {
right--;
}
}
if (left_visit == true && right_visit == true && left <= right) {
temp = letters[right];
letters[right] = letters[left];
letters[left] = temp;
left++;
right--;
left_visit = false;
right_visit = false;
}
}
System.out.print(new String(letters));
}
X. Not good - space O(n) public String reverseVowels(String input){
@SuppressWarnings("rawtypes")
ArrayList vowels = new ArrayList();
char[] arr = input.toCharArray();
int sizeOfarr = input.length();
for(int i=0 ; i< sizeOfarr; i++){
if(arr[i] == 'a'|| arr[i] == 'e' || arr[i] == 'i'||arr[i] == 'o'||arr[i] == 'u'){
vowels.add(i);
}
}
int sizeOfVowels = vowels.size();
for(int j=0 ; j< sizeOfVowels/2; j++){
//index for (last - curr) value in the set 'vowels'
int k = sizeOfVowels - 1 - j;
int incIndex = (int)vowels.get(j);
int decIndex = (int)vowels.get(k);
char temp = arr[incIndex];
arr[incIndex] = arr[decIndex];
arr[decIndex] = temp;
//System.out.println(Arrays.toString(arr));
}
return Arrays.toString(arr);
}
Read full article from Write code to reverse vowels o | CareerCup