码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-02-20 01:21:34      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:http   题意   时间   har   pop   方法   str   margin   int   

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:




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

标签:http   题意   时间   har   pop   方法   str   margin   int   

原文地址:http://www.cnblogs.com/xiejunzhao/p/f48165e05c104dd1e5fc71f231956abb.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!