【leetcode】344. Reverse String

题目

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

Example:

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

问题陈述:

字符串翻转

题目思路:

  1. 反向遍历,输入到另一个string中,复杂度$O(n)$
  2. 看了tag中有two pointers,一个从前往后一个从后往前,交换数值,复杂度减少一半$O(n/2)$

算法复杂度:O(n)

代码:

class Solution {//反向遍历输入另一个string
public:
string reverseString(string s) {
string result = "";
int len = s.size();
for (int i = len - 1; i >= 0; i--) {
result += s[i];
}
return result;
}
};
class Solution {//two pointer
public:
string reverseString(string s) {
for(auto iter = 0; iter < s.size() / 2; ++iter)
swap(s[iter], s[s.size() - 1 - iter]);
return s;
}
};

结果