码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Reverse Vowels of a String

时间:2016-05-15 12:36:48      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

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);
    }
}

[LeetCode] Reverse Vowels of a String

标签:

原文地址:http://blog.csdn.net/foreverling/article/details/51416331

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!