java面试题(3)

来源:互联网 发布:空间日志转载软件 编辑:程序博客网 时间:2024/05/22 02:05

原题:

// 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) {        if(s == null || s.length() == 0) return s;        String vowels = "aeiouAEIOU";        char[] chars = s.toCharArray();        int start = 0;        int end = s.length() - 1;        while(start < end) {            while(start < end && !vowels.contains(chars[start] + "")) {                start++;            }            while(start < end && !vowels.contains(chars[end] + "")) {                end--;            }            char temp = chars[start];            chars[start] = chars[end];            chars[end] = temp;            start++;            end--;        }        return new String(chars);    }}
原创粉丝点击