【LeetCode】Reverse Vowels of a String 解题报告

Reverse Vowels of a String

[LeetCode]

https://leetcode.com/problems/reverse-vowels-of-a-string/

Total Accepted: 7758 Total Submissions: 22132 Difficulty: Easy

Question

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

Ways

理解题意很重要啊!

这个题的意思是把收尾向中间走的时候遇到的所有元音字符换位置。也就是说 “abecui”–>”ibucea”;

刚开始以为是把最中间的两个换位置了。说明题目给的例子不太能说明问题。

也就是用双指针的方法。一个从头查找,一个从尾查找。同时判断是否为元音字符,如果两个指针都是落在了原因字符上的时候,交换。别忘了交换位置之后前往下一个地点。

因为用到了list,所以效率比较低。

public class Solution {
    public String reverseVowels(String s) {
        ArrayList<Character> list=new ArrayList();
        list.add('a');
        list.add('e');
        list.add('i');
        list.add('o');
        list.add('u');
        list.add('A');
        list.add('E');
        list.add('I');
        list.add('O');
        list.add('U');

        char[] array=s.toCharArray();

        int head=0;
        int tail=array.length-1;

        while(head<tail){
            if(!list.contains(array[head])){
                head++;
                continue;
            }
            if(!list.contains(array[tail])){
                tail--;
                continue;
            }
            char temp=array[head];
            array[head]=array[tail];
            array[tail]=temp;

            head++;
            tail--;
        }

        return new String(array);
    }

}

AC:11ms

Date

2016/5/1 20:52:19

你可能感兴趣的:(LeetCode)