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;
}
- #leetcode# 344 Reverse String
- Leetcode Reverse String 344
- LeetCode 344 Reverse String
- LeetCode 344 Reverse String
- LeetCode 344 Reverse String
- [leetcode 344]Reverse String
- LeetCode 344:Reverse String
- leetcode 344 Reverse String
- LeetCode-344 Reverse String
- leetcode 344 Reverse String
- leetcode 344 Reverse String
- LeetCode-344:Reverse String
- LeetCode 344 Reverse String
- LeetCode#344 Reverse String
- Leetcode-344-Reverse String
- Leetcode #344 Reverse String
- leetcode-344- Reverse String
- Leetcode 344 Reverse String
- 命令行式下java package的编译与运行注意事项
- Codeforces 676C Vasya and String 尺取法
- Quartz以及代码实现--可以实现定时器效果
- Word Pattern
- java连接Sql server 2008步骤
- LeetCode-344 Reverse String
- eclipse将一段代码抽取为方法Extract Method
- static
- Spring web mvc DispatcherServlet (1)---配置
- 第13期 《与这世界交手》16年5月刊
- [Android] android.app.Activity.findViewById(int) on a null object reference
- 异常典型编程题
- JavaScript---网络编程(4)-Date、Math、Global和自定义对象
- 向下转型