leetcode笔记:Reverse Vowels of a String

来源:互联网 发布:php带采集小说系统 编辑:程序博客网 时间:2024/04/28 20:47

一. 题目描述

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

二. 题目分析

题目大意是,编写函数输入一个字符串,将其中的元音字母反转,其他字母位置不变。

这里只实现了一种方法,比较无脑。使用leftright记录遍历字符串的左右下标,如果不是原因字母,直接跳过。当且仅当left < right且当且leftright下标所指元素均为元音时才翻转顺序。

判断当前字符是否为原因时,使用了一个模式字符串temp,如果在模式字符串中没找到,则返回:string::npos

三. 示例代码

class Solution {public:    string reverseVowels(string s) {        int left = 0, right = s.size() - 1;        string temp = "aeiouAEIOU";        while (left < right)        {            while (left < right && temp.find(s[left]) == string::npos) ++left;            while (left < right && temp.find(s[right]) == string::npos) --right;            if(left < right) swap(s[left++], s[right--]);        }        return s;    }};

四. 小结

有更好的方法,欢迎交流。

1 0
原创粉丝点击