首页 > 代码库 > 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) 
  1. static public string ReverseVowels(string s) {
  2. Stack<char> vowelsStack = new Stack<char>();
  3. for (int i = 0; i < s.Length; i++) {
  4. char c = s[i];
  5. if (c == ‘a‘ || c == ‘e‘ || c == ‘i‘ || c == ‘o‘ || c == ‘u‘ ||
  6. c == ‘A‘ || c == ‘E‘ || c == ‘I‘ || c == ‘O‘ || c == ‘U‘) {
  7. vowelsStack.Push(c);
  8. }
  9. }
  10. string rsult = "";
  11. for (int i = 0; i < s.Length; i++) {
  12. char c = s[i];
  13. if (c == ‘a‘ || c == ‘e‘ || c == ‘i‘ || c == ‘o‘ || c == ‘u‘ ||
  14. c == ‘A‘ || c == ‘E‘ || c == ‘I‘ || c == ‘O‘ || c == ‘U‘) {
  15. rsult += vowelsStack.Pop();
  16. } else {
  17. rsult += c;
  18. }
  19. }
  20. return rsult;
  21. }

方法2:


null


345. 反转字符串中元音字母的位置 Reverse Vowels of a String