Skip to content

Commit 9fa704f

Browse files
committed
Add solution 344
1 parent 2b8d742 commit 9fa704f

File tree

3 files changed

+61
-0
lines changed

3 files changed

+61
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ Complete solutions to Leetcode problems, updated daily.
2222
| 198 | [House Robber](https://github.com/yanglbme/leetcode/tree/master/solution/198.House%20Robber) | `Dynamic Programming` |
2323
| 203 | [Remove Linked List Elements](https://github.com/yanglbme/leetcode/tree/master/solution/203.Remove%20Linked%20List%20Elements) | `Linked List` |
2424
| 237 | [Delete Node in a Linked List](https://github.com/yanglbme/leetcode/tree/master/solution/237.Delete%20Node%20in%20a%20Linked%20List) | `Linked List` |
25+
| 344 | [Reverse String](https://github.com/yanglbme/leetcode/tree/master/solution/344.Reverse%20String) | `Two Pointers`, `String` |
2526
| 876 | [Middle of the Linked List](https://github.com/yanglbme/leetcode/tree/master/solution/876.Middle%20of%20the%20Linked%20List) | `Linked List` |
2627

2728

solution/344.Reverse String/README.md

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
## 反转字符串
2+
### 题目描述
3+
4+
编写一个函数,其作用是将输入的字符串反转过来。
5+
6+
示例 1:
7+
```
8+
输入: "hello"
9+
输出: "olleh"
10+
```
11+
12+
示例 2:
13+
```
14+
输入: "A man, a plan, a canal: Panama"
15+
输出: "amanaP :lanac a ,nalp a ,nam A"
16+
```
17+
18+
### 解法
19+
本题利用双指针解决。
20+
21+
```java
22+
class Solution {
23+
public String reverseString(String s) {
24+
if (s == null || s.length() < 2) {
25+
return s;
26+
}
27+
char[] chars = s.toCharArray();
28+
int p = 0;
29+
int q = chars.length - 1;
30+
while (p < q) {
31+
char tmp = chars[p];
32+
chars[p] = chars[q];
33+
chars[q] = tmp;
34+
++p;
35+
--q;
36+
}
37+
return String.valueOf(chars);
38+
}
39+
40+
}
41+
```
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
public String reverseString(String s) {
3+
if (s == null || s.length() < 2) {
4+
return s;
5+
}
6+
char[] chars = s.toCharArray();
7+
int p = 0;
8+
int q = chars.length - 1;
9+
while (p < q) {
10+
char tmp = chars[p];
11+
chars[p] = chars[q];
12+
chars[q] = tmp;
13+
++p;
14+
--q;
15+
}
16+
return String.valueOf(chars);
17+
}
18+
19+
}

0 commit comments

Comments
 (0)