344. Reverse String

  • 59.4%

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

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

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

方法一:

我的代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
string reverseString(string s) {
if(s.empty()) return s;
int l=0, r=s.size()-1;
while(l<r){
swap(s[l], s[r]);
l++;
r--;
}
return s;
}
};

12ms, Apr.23rd, 2016

1
2
3
4
5
6
7
8
9
10
class Solution {
public:
string reverseString(string s) {
int i = 0, j = s.size() - 1;
while(i < j){
swap(s[i++], s[j--]);
}
return s;
}
};

python

https://discuss.leetcode.com/topic/58719/python-3-solutions-recursive-classic-pythonic

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# recursive
class Solution(object):
def reverseString(self, s):
l = len(s)
if l < 2:
return s
return self.reverseString(s[l/2:]) + self.reverseString(s[:l/2])

# classic
class SolutionClassic(object):
def reverseString(self, s):
r = list(s)
i, j = 0, len(r) - 1
while i < j:
r[i], r[j] = r[j], r[i]
i += 1
j -= 1

return "".join(r)

# pythonic
class SolutionPythonic(object):
def reverseString(self, s):
return s[::-1]

java

https://discuss.leetcode.com/topic/43296/java-simple-and-clean-with-explanations-6-solutions

https://discuss.leetcode.com/topic/43296/java-simple-and-clean-with-explanations-6-solutions

https://discuss.leetcode.com/topic/44869/java-easiest-method-2-line-code-attached-another-method

https://discuss.leetcode.com/topic/43305/java-swapping-char-array

谢谢你,可爱的朋友。