345. Reverse Vowels of a String

来源:互联网 发布:服务器网络拓扑图图片 编辑:程序博客网 时间:2024/06/10 20:21

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

Note:
The vowels does not include the letter "y".

一开始的想法是元音找出来,在倒序相加,但是这样太慢了。

public class Solution {
    public String reverseVowels(String s) {
        char[] total=s.toCharArray();
        StringBuilder sb=new StringBuilder();
        StringBuilder t=new StringBuilder();
        if(s==null)
        return null;
        int vowel=0;
        for(char e:total){
           vowel=e-'A';
        if(vowel==0||vowel==4||vowel==8||vowel==14||vowel==20||vowel==32||vowel==36||vowel==40||vowel==46||vowel==52)
        t.append(e);
        }
        int count=t.length()-1;
        for(int i=0;i<s.length();i++){
        vowel=s.charAt(i)-'A';
        if(vowel==0||vowel==4||vowel==8||vowel==14||vowel==20||vowel==32||vowel==36||vowel==40||vowel==46||vowel==52){
        sb.append(t.charAt(count--));
        }
        else{
        sb.append(s.charAt(i));
        }
        }
    return sb.toString();
    }
}


直接将首尾两端的元音字符交换位置。

public class Solution {

static final String vowels = "aeiouAEIOU";
public String reverseVowels(String s) {
    int first = 0, last = s.length() - 1;
    char[] array = s.toCharArray();
    while(first < last){
        while(first < last && vowels.indexOf(array[first]) == -1){
            first++;
        }
        while(first < last && vowels.indexOf(array[last]) == -1){
            last--;
        }
        char temp = array[first];
        array[first] = array[last];
        array[last] = temp;
        first++;
        last--;
    }
    return new String(array);
}
}
0 0
原创粉丝点击