LeetCode-344 Reverse String

来源:互联网 发布:亦何为而非天下之公乎 编辑:程序博客网 时间:2024/05/22 13:35

https://leetcode.com/problems/reverse-string/

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

Example:

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


1、第一反应...for循环逆序

class Solution {
public:
    string reverseString(string s) {
        string t;
        int sLen = s.length();
        for(int i = 0;i<sLen;i++){
            cout << s[sLen - i - 1];
            t[i] = s[sLen - i - 1];
        }
        return t;
    }
};

结果Runtime Error,调试发现string t定义的t = “”;改成string t = s;后发现Accepted了

(12ms)

class Solution {
public:
    string reverseString(string s) {
        string t = s;
        int sLen = s.length();
        for(int i = 0;i<sLen;i++){
            t[i] = s[sLen - i - 1];
        }
        return t;
    }
};

2、查资料发现C++ STL中有reverse()函数

(16ms)

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

// STL 反转函数 reverse() 的实现
    /*     template <class BidirectionalIterator>
     *     void reverse(BidirectionalIterator first, BidirectionalIterator last)
     *     {
     *         while ((first != last) && (first != --last))
     *             swap(*first++, *last);
     *     }
     */

--------------C++源码1---------------

#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <string>
using namespace std;
int main(){
string s;
cin >> s;
string t = s;
int sLen = s.length();
for (int i = 0; i < sLen; i++){
t[i] = s[sLen - i - 1];
}
cout << t << endl;
system("pause");
return 0;
}

--------------C++源码2---------------

#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <string>
using namespace std;
int main(){
string s;
cin >> s;
reverse(s.begin(), s.end());
cout << s << endl;
system("pause");
return 0;
}


0 0
原创粉丝点击