leetcode 345. Reverse Vowels of a String 反转字符串元音字符

来源:互联网 发布:对外贸易数据 编辑:程序博客网 时间:2024/05/21 01:56

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

这道题考察的是反转一个字符串中的所有的元音字符,使用双指针,然后交换即可。

代码如下:

/* * 双向指针,一次遍历即可,交换所有的元音字符 * */class Solution {     public String reverseVowels(String s)         {            StringBuilder builder=new StringBuilder(s);            int i=0;            int j=builder.length()-1;            while(i<j)            {                boolean a=isVowel(builder.charAt(i));                boolean b=isVowel(builder.charAt(j));                if(a&&b)                {                    char tmp=builder.charAt(i);                    builder.setCharAt(i, builder.charAt(j));                    builder.setCharAt(j, tmp);                    i++;                    j--;                }else if(a && !b)                    j--;                else if(!a && b)                    i++;                else                 {                    i++;                    j--;                }            }            return builder.toString();    }    public boolean isVowel(char a)     {        if(a=='a'||a=='e'||a=='i'||a=='o'||a=='u'         ||a=='A'||a=='E'||a=='I'||a=='O'||a=='U')            return true;        else            return false;    }}
阅读全文
0 0
原创粉丝点击