首页 > 其他 > 详细

[LeetCode] Reverse Vowels of a String

时间:2016-05-15 12:36:14      阅读:173      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!