题目描述【Leetcode】
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = “hello”, return “olleh”.
这道题就是倒置字符串
方法一:用reverse函数简单粗暴:
class Solution {
public:
string reverseString(string s) {
int len = s.length();
reverse(&s[0],&s[len]);
return s;
}
};
方法二:一点一点换,这个办法比第一个要快
class Solution {
public:
string reverseString(string s) {
int len = s.length();
for(int i = 0; i < len/2; i++){
swap(s[i],s[len-i-1]);
}
return s;
}
};
本文介绍了一道LeetCode上的经典题目——字符串倒置的两种实现方法。一种是使用reverse函数直接完成倒置,另一种是通过逐个元素交换的方式进行,后者在效率上更优。
525

被折叠的 条评论
为什么被折叠?



