2
头图

Reverse vowels in a string

Title description: Write a function that takes a string as input and reverses the vowels in the string.

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/reverse-vowels-of-a-string/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Reverse stack order
  • First initialize the vowels list vowels;
  • Then loop to determine each character in s, and put the vowels into the stack in turn;
  • Then loop s again, and replace the vowels that appear with the top element after popping out of the stack;
  • After the loop processing is completed, it is the reversed character string.
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class LeetCode_345 {
    /**
     * 元音字母列表
     */
    private static List<Character> vowels = new ArrayList<>();

    static {
        // 初始化所有的元音字母
        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)) {
                // 将元音字母放入栈中
                vowelStack.push(c);
            }
        }
        for (int i = 0; i < sList.length; i++) {
            if (vowels.contains(sList[i])) {
                // 将元音字母从栈中取出,倒序取出
                sList[i] = vowelStack.pop();
            }
        }
        return new String(sList);
    }

    public static void main(String[] args) {
        System.out.println(reverseVowels("hello"));
    }
}
[Daily Message] No matter what others think, I will never interrupt my rhythm, and I can naturally stick to the things I like.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!