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:使用两个指针,时间复杂度为O(n/2)
  1. public class Solution {
  2. public string ReverseVowels(string s) {
  3. char[] cArr = s.ToArray();
  4. int l = 0, r = s.Length - 1;
  5. while (l < r) {
  6. while (l < r && !IsVowels(cArr[l])) l++;
  7. while (l < r && !IsVowels(cArr[r])) r--;
  8. char temp = cArr[l];
  9. cArr[l] = cArr[r];
  10. cArr[r] = temp;
  11. l++;
  12. r--;
  13. }
  14. return new string(cArr);
  15. }
  16. public bool IsVowels(char c) {
  17. return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U');
  18. }
  19. }





posted @ 2017-02-20 00:06  xiejunzhao  阅读(196)  评论(0编辑  收藏  举报