[LeetCode] Reverse Vowels of a String

简介: Write a function that takes a string as input and reverse only the vowels of a string.Example 1: Given s = “hello”, return “holle”.Example 2: Given s = “leetcode”, return “leotcede”.

Write a function that takes a string as input and reverse only the vowels of a string.

Example 1:
Given s = “hello”, return “holle”.

Example 2:
Given s = “leetcode”, return “leotcede”.

解题思路

双指针,一个往前移动,一个往后移动,找到元音字母时则交换。

实现代码

// Runtime: 12 ms
public class Solution {
    private static final String STR = "aeiouAEIOU";
    private static final Set<Character> VOWELS = new HashSet<Character>(STR.length());
    static {
        for (int i = 0; i < STR.length(); i++) {
            VOWELS.add(STR.charAt(i));
        }
    }

    public String reverseVowels(String s) {
        StringBuilder sb = new StringBuilder(s);
        int left = 0;
        int right = sb.length() - 1;
        while (left < right) {
            while (left < right && !isVowels(sb.charAt(left))) {
                ++left;
            }
            while (left < right && !isVowels(sb.charAt(right))) {
                --right;
            }

            char temp = sb.charAt(left);
            sb.setCharAt(left++, sb.charAt(right));
            sb.setCharAt(right--, temp);
        }
        return sb.toString();
    }

    private boolean isVowels(char ch) {
        return VOWELS.contains(ch);
    }
}
目录
相关文章
|
7月前
CF1553B Reverse String(数学思维)
CF1553B Reverse String(数学思维)
23 0
|
3月前
|
Go 机器学习/深度学习 Rust
Golang每日一练(leetDay0119) 反转字符串I\II Reverse String
Golang每日一练(leetDay0119) 反转字符串I\II Reverse String
36 0
Golang每日一练(leetDay0119) 反转字符串I\II Reverse String
|
机器学习/深度学习 NoSQL 算法
LeetCode 344. 反转字符串 Reverse String
LeetCode 344. 反转字符串 Reverse String
LeetCode 206. 反转链表 Reverse Linked List
LeetCode 206. 反转链表 Reverse Linked List
|
机器学习/深度学习 NoSQL
LeetCode 344. Reverse String
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。 不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
70 0
LeetCode 344. Reverse String
LeetCode 190. Reverse Bits
颠倒给定的 32 位无符号整数的二进制位。
63 0
LeetCode 190. Reverse Bits
LeetCode之Reverse String II
LeetCode之Reverse String II
84 0
LeetCode之Reverse String
LeetCode之Reverse String
71 0
LeetCode之Reverse Integer
LeetCode之Reverse Integer
78 0
LeetCode 150:逆波兰表达式求值 Evaluate Reverse Polish Notation
题目: 根据逆波兰表示法,求表达式的值。 有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。 Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, /. Each operand may be an integer or another expression. 说明: 整数除法只保留整数部分。
1354 0