Leetcode题解14 345. 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”.

public class Solution {
    public static String reverseVowels(String s) {
        String ss = "aeiouAEIOU";
        StringBuilder sb = new StringBuilder();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (ss.contains(s.charAt(i) + "")) {
                sb.append(s.charAt(i));
            }
        }
        String temp = sb.reverse().toString();
        int pos = 0;
        for (int i = 0; i < s.length(); i++) {
            if (!ss.contains(s.charAt(i) + "")) {
                result.append(s.charAt(i));
            } else {
                result.append(temp.charAt(pos));
                pos++;
            }
        }
        return result.toString();
    }
}

你可能感兴趣的:(LeetCode)