leetcode 345. Reverse Vowels of a String 只反转字符串元音字符
2017-10-02 18:07
519 查看
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”.
这道题考察的是反转一个字符串中的所有的元音字符,使用双指针,然后交换即可。
代码如下:
下面是C++的做法,遍历即可
代码如下:
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; } }
下面是C++的做法,遍历即可
代码如下:
#include <iostream> #include <vector> #include <map> #include <unordered_map> #include <set> #include <unordered_set> #include <queue> #include <stack> #include <string> #include <climits> #include <algorithm> #include <sstream> #include <functional> #include <bitset> #include <numeric> #include <cmath> #include <regex> using namespace std; class Solution { public: string reverseVowels(string s) { if (s.length() <= 0) return s; int i = 0, j = s.length() - 1; while (i < j) { bool a = isVowels(s[i]); bool b = isVowels(s[j]); if (a == true && b == true) { swap(s[i], s[j]); i++; j--; }else if (a == true && b == false) j--; else if (a == false && b == true) i++; else { i++; j--; } } return s; } bool isVowels(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; } };
相关文章推荐
- LeetCode Reverse Vowels of a String(字符串中元音字符反转)
- LeetCode 345 反转元音字符串
- leetcode_345. Reverse Vowels of a String 转换字符串中的元音字符,list类型数据转换成str类型,join()函数
- [Leetcode,python] Reverse String 反转字符串
- [LeetCode] minimum window 包含所有字符的最小子字符串
- [leetcode, python] Reverse Words in a String 反转字符串
- LeetCode 387. First Unique Character in a String (字符串中的第一个唯一字符)
- java中两个字符交换内容(可用于字符串反转)
- 轻松python文本专题-字符串逐字符反转以及逐单词反转
- [LeetCode] Isomorphic Strings - 字符串操作:数组计数字符个数问题
- [LeetCode] First Unique Character in a String 字符串第一个不同字符
- LeetCode按单词反转字符串
- leetcode Reverse Words in a String III 反转字符串中的单词
- [Leetcode,python] Reverse String 反转字符串
- sql 操作字符串 取多个字符为最后一个后面的数据 用reverse反转字符
- [leetcode, python] Reverse Words in a String 反转字符串
- python_11(format、转义字符、连接字符、字符串操作函数、字符串反转)
- 元音字母的字符串反转
- LeetCode——344. Reverse String(字符串反转)
- C++学习笔记——erase删除字符串中特定字符 由leetcode383题想到的