首页 > 代码库 > 345. 反转字符串中元音字母的位置 Reverse Vowels of a String
345. 反转字符串中元音字母的位置 Reverse Vowels of a String
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"
题意:反转字符串中元音字母的位置
方法1:用栈保存元音字符串,时间复杂度为O(2n)
static public string ReverseVowels(string s) {
Stack<char> vowelsStack = new Stack<char>();
for (int i = 0; i < s.Length; i++) {
char c = s[i];
if (c == ‘a‘ || c == ‘e‘ || c == ‘i‘ || c == ‘o‘ || c == ‘u‘ ||
c == ‘A‘ || c == ‘E‘ || c == ‘I‘ || c == ‘O‘ || c == ‘U‘) {
vowelsStack.Push(c);
}
}
string rsult = "";
for (int i = 0; i < s.Length; i++) {
char c = s[i];
if (c == ‘a‘ || c == ‘e‘ || c == ‘i‘ || c == ‘o‘ || c == ‘u‘ ||
c == ‘A‘ || c == ‘E‘ || c == ‘I‘ || c == ‘O‘ || c == ‘U‘) {
rsult += vowelsStack.Pop();
} else {
rsult += c;
}
}
return rsult;
}
方法2:
null
345. 反转字符串中元音字母的位置 Reverse Vowels of a String
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。