zoukankan      html  css  js  c++  java
  • LeetCode 345. Reverse Vowels of a String

    https://leetcode.com/problems/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".

    两个指针,查找交换字符。一开始忘记在SWAP之后,移动指针了,导致死循环。。。新学到一个string::npos indicates no matches。

     1 #include <iostream>
     2 using namespace std;
     3 
     4 class Solution {
     5 public:
     6 /*
     7     bool isVowels(char chIn)
     8     {
     9         return ((toupper(chIn) == 'A' || toupper(chIn) == 'E' || toupper(chIn) == 'I' || toupper(chIn) == 'O' || toupper(chIn) == 'U'));
    10     }
    11 */
    12     
    13     string reverseVowels(string s) {
    14         int i = 0, j = s.length() - 1;
    15         string sVowels = "aeiouAEIOU";
    16 
    17         // Remember special case
    18         if (s == "" || s.length() == 0) return s;
    19         
    20         while (i < j)
    21         {
    22 //            while (!isVowels(s[i]) && (i < j)) i ++;
    23               while ((sVowels.find(s[i]) == string::npos) && (i < j)) i ++;
    24 //            while (!isVowels(s[j]) && (i < j)) j --;
    25               while ((sVowels.find(s[j]) == string::npos) && (i < j)) j --;  
    26                         
    27             if (i < j)
    28                 swap(s[i], s[j]);
    29             
    30             i ++;
    31             j --;
    32         }
    33 
    34         return s;
    35     }
    36 };
    37 
    38 int main ()
    39 {
    40     Solution testSolution;
    41     string result;
    42     
    43     result = testSolution.reverseVowels("hello");    
    44     cout << result << endl;
    45     
    46     char ch;
    47     cin >> ch;
    48     
    49     return 0;
    50 }
    View Code

    string::find - C++ Reference

    http://www.cplusplus.com/reference/string/string/find/

    string::npos - C++ Reference

    http://www.cplusplus.com/reference/string/string/npos/

  • 相关阅读:
    阅读ARm芯片手册 阅读方法
    Linux驱动mmap内存映射
    Linux下inotify的基本使用及注意事项
    网络视频监控与人脸识别
    Linux pci驱动源码
    Verilog语法
    跟着我从零开始入门FPGA(一周入门XXOO系列)-1、Verilog语法
    周立功-我的25年嵌入式生涯
    Linux 进程学习
    [转]MFC下关于“建立空文档失败”问题的分析
  • 原文地址:https://www.cnblogs.com/pegasus923/p/5510740.html
Copyright © 2011-2022 走看看