Reverse Vowels of a String 交换元音字母

来源:互联网 发布:企业电话查询软件 编辑:程序博客网 时间:2024/05/21 01:44

题目要求:

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

Subscribe to see which companies asked this question

元音字母是 i o e a u,考察是否是元音字母时应该   新建一个字符串,其中包含了所有元音字母  以及大小写,这样才可以减少比较的次数。


public static String reverseVowels(String s) {        char[] st=s.toCharArray();        String vowels = "aeiouAEIOU";        int i=0;        int j=st.length-1;        while(i<j)        {            while(i<j && !vowels.contains(st[i]+""))            {i++;}            while(i<j && !vowels.contains(st[j]+""))            {j--;}            char temp=st[i];st[i]=st[j];st[j]=temp;            i++;j--;        }        return new String(st);    }


0 0
原创粉丝点击