zoukankan      html  css  js  c++  java
  • 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. }





  • 相关阅读:
    如何为基于windows验证的站点的某个页面、文件或文件夹单独设置匿名访问
    JMeter基础
    selenium select操作及其他补充
    HTML面试
    第一天
    AspNetPager 7.4.2版发布
    java移位运算copy来的。为了备忘
    android 开发中的错误
    启动android模拟器报错
    最省内存的方式加载图片资源
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/f48165e05c104dd1e5fc71f231956abb.html
Copyright © 2011-2022 走看看