<LeetCode OJ> 345 / 344 Reverse Vowels of a String / Reverse String

345 Reverse Vowels of a String
Total Accepted: 537  Total Submissions: 1488  Difficulty: Easy

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".


分析:DONE

典型的双指针问题:从前从后分别寻找(利用set加快查找速度)元音的位置,然后交换,注意边界条件即可!

class Solution {
public:
    void swapchar(string &str,int pos1,int pos2)  
    {  
        char tmpch=str[pos2];  
        str[pos2]=str[pos1];  
        str[pos1]=tmpch;  
    }  
    string reverseVowels(string s) {
        char base[10]={'a','e','i','o','u','A','E','I','O','U'};
        set<char> seting(base,base+10);
        int startpos=0,endpos=s.size()-1;
        while(startpos < endpos )
        {
            while( startpos < endpos && seting.find(s[startpos]) == seting.end())//从左往右、新的、未被交换过的元音位置
                startpos++;
            while( startpos < endpos && seting.find(s[endpos]) == seting.end())
                endpos--;
            if(startpos < endpos)    
                swapchar(s,startpos++,endpos--);    
        }
        return s;
    }
};




344 Reverse String

Total Accepted: 598  Total Submissions: 936  Difficulty: Easy

Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "olleh".


分析:DONE

字符串反转!恐怕此题会成为leetcode历史上最简单的题目!

时间复杂度o(n)

class Solution {
public:
    void swapchar(string &str,int pos1,int pos2)
    {
        char tmpch=str[pos2];
        str[pos2]=str[pos1];
        str[pos1]=tmpch;
    }
    string reverseString(string s) {
        int halfsize=s.size()/2;
        for(int i=0;i < halfsize;i++)
            swapchar(s,i,s.size()-i-1);
        return s;
    }
};

或者:

class Solution {
public:
    string reverseString(string s) {
        reverse(s.begin(), s.end());
        return s;
    }
};



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.csdn.net/ebowtang/article/details/51228095

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值