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


转载请注明出处:http://blog.csdn.net/crazy1235/article/details/51429823


Subject

出处:https://leetcode.com/problems/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”.


Explain

该题目的意思是反转一个字符串中的元音字母。第一个和最后一个元音字母交换,第二个和倒数第二个交换……


My Solution

首先定义一个方法去判断一个char字符是否是元音字母。然后通过首尾两个”指针”,当前后两个字符都是元音字符的时候才进行交换,否则将不是元音字符的指针向前或者向后移动。

跳出条件就是start < end。


    /**
     * 
     * @param c
     * @return
     */
    public static boolean checkVowel(char c) {
        if ('a' == c || 'e' == c || 'i' == c || 'o' == c || 'u' == c
                || 'A' == c || 'E' == c || 'I' == c || 'O' == c || 'U' == c) {
            return true;
        }
        return false;
    }

    /**
     * 
     * @param s
     * @return
     */
    public static String reverseVowels(String s) {
        char[] ch = s.toCharArray();
        int start = 0;
        int end = ch.length - 1;
        char temp;
        while (start < end) {
            if (checkVowel(ch[start]) && checkVowel(ch[end])) {
                temp = ch[end];
                ch[end] = ch[start];
                ch[start] = temp;
                start++;
                end--;
            } else {
                if (!checkVowel(ch[start])) {
                    start++;
                }
                if (!checkVowel(ch[end])) {
                    end--;
                }
            }
        }
        return new String(ch);
    }

so easy~

你可能感兴趣的:(Java开发,算法学习,LeetCode解题报告,Java,篇)