Leetcode #345. Reverse Vowels of a String 逆转元音字母 解题报告

1 解题思想

这道题是逆转字符串的一个变种,要求的只是把元音的部分进行逆转,非元音的地方不进行逆转。

所以基本的思想就是:
1、单独的扫描一次元音,得道其序列(我们可以逆序扫描,这样读出的时候直接就是逆序咯)
2、对元音序列和剩余的字符串进行单独处理

2 原题

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”.

Subscribe to see which companies asked this question

3 AC解

public class Solution {
    /** * * 这道题就只针对元音部分逆转 * 1、那么我们首先需要从尾巴遍历,将将元音部分提取出来作为一个特殊部分 * 2、然后正着输出,此时遇到元音就从1中的部分按照顺序提取(当时是逆序提取,现在就直接相当于逆转了),不是元音就原来的部分就好 * * 注意大小写。 * */
    public String reverseVowels(String s) {
        StringBuilder vowels=new StringBuilder();
        String sl=s.toLowerCase();
        for(int i=sl.length()-1;i>=0;i--) {
                char tmp=sl.charAt(i);
                if(tmp=='a' || tmp=='e' || tmp=='i' || tmp=='o' || tmp=='u'){
                    vowels.append(s.charAt(i));
                }
            }
        StringBuilder result=new StringBuilder();
        String rvowels=vowels.toString();
        int index=0;
        for(int i=0;i<sl.length();i++){
            char tmp=sl.charAt(i);
                if(tmp=='a' || tmp=='e' || tmp=='i' || tmp=='o' || tmp=='u'){
                    result.append(rvowels.charAt(index++));
                } else{
                    result.append(s.charAt(i));
                }
        }
        return result.toString();
    }
}

你可能感兴趣的:(LeetCode,字符串,逆转,元音)