博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Reverse Vowels of a String
阅读量:6870 次
发布时间:2019-06-26

本文共 1645 字,大约阅读时间需要 5 分钟。

Problem

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

第一种解法:将字符串转化为字符数组,用一头一尾两个指针向中间夹逼,遇到两个元音字母就进行位置交换。

第二种解法:相同的思路,一头一尾两个指针向中间夹逼。头指针是元音字母时,用尾指针找到最靠后的元音字母,并不断将靠后的元音字母加入StringBuilder;头指针是非元音字母时,就顺序放入非元音字母。
这样,只用头指针放非元音字母,只用尾指针放元音字母。
注意只有当头指针为元音字母时,才会操作尾指针。判断尾指针非元音字母的条件:
while (j >= 0 && "AEIOUaeiou".indexOf(s.charAt(j)) == -1) j--;

Solution

1. Two Pointers --6ms

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);    }}

2. StringBuilder --15ms

public class Solution {    public String reverseVowels(String s) {        StringBuilder sb = new StringBuilder();        int j = s.length() - 1;        for (int i = 0; i < s.length(); i++) {            if ("AEIOUaeiou".indexOf(s.charAt(i)) != -1) {                while (j >= 0 && "AEIOUaeiou".indexOf(s.charAt(j)) == -1) j--;                sb.append(s.charAt(j));                j--;            }            else sb.append(s.charAt(i));        }        return sb.toString();    }}

转载地址:http://xepfl.baihongyu.com/

你可能感兴趣的文章
web前端自动化测试利器puppeteer介绍
查看>>
Mac怎么生成.ssh文件
查看>>
“C语言” 读书札记(四)之[再续编译执行]
查看>>
[CODE] Dahua Lin贡献的两个开源软件
查看>>
高斯消元法求解线性方程组的解集
查看>>
C++ 沉思录——Chap5:代理类
查看>>
通向架构师的道路(第一天)之Apache整合Tomcat - lifetragedy的专栏 - 博客频道 - CSDN.NET...
查看>>
DD-WRT v24-sp2的WDS中继设置
查看>>
SQL语句中ALTER的用法
查看>>
最近读的javascript,一些文章
查看>>
SVN服务器搭建和使用(三)
查看>>
JSON入门指南--客户端处理JSON
查看>>
Objective-C内存布局
查看>>
qsort的另类玩法,无聊写着耍耍
查看>>
每日一乐,健康多滋味~~
查看>>
[Oracle] - Connect to a PDB of Oracle12c
查看>>
VS2015 android 设计器不能可视化问题解决。
查看>>
移动数据统计平台分析
查看>>
httppp 1.4.0 发布,HTTP响应时间监控
查看>>
ASP.NET MVC加载ASCX之后,并为之赋值
查看>>