Invert a vowel in a string
Write a function that takes a string as input and inverts the vowels in the string.
Examples can be found on the LeetCode website.
Source: LeetCode link: leetcode-cn.com/problems/re… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.
Solution 1: stack in reverse order
First initialize the vowels list.
Then loop through each character in s, placing the vowels in turn on the stack;
Then loop s again, replace the vowel letter with the top element of the stack;
When the loop is complete, the string is reversed.
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class LeetCode_345 {
/** * list of vowels */
private static List<Character> vowels = new ArrayList<>();
static {
// Initialize all vowels
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
vowels.add('A');
vowels.add('E');
vowels.add('I');
vowels.add('O');
vowels.add('U');
}
public static String reverseVowels(String s) {
if (s == null || s.length() < 2) {
return s;
}
char[] sList = s.toCharArray();
Stack<Character> vowelStack = new Stack<>();
for (char c : sList) {
if (vowels.contains(c)) {
// Put vowels on the stackvowelStack.push(c); }}for (int i = 0; i < sList.length; i++) {
if (vowels.contains(sList[i])) {
// Remove vowels from stack, in reverse ordersList[i] = vowelStack.pop(); }}return new String(sList);
}
public static void main(String[] args) {
System.out.println(reverseVowels("hello")); }}Copy the code
No matter what others think, I will never break my rhythm. I can stick to what I like naturally.