Skip to content

Commit 9d0d6f8

Browse files
committed
翻转字符串
1 parent 82e7549 commit 9d0d6f8

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,7 @@
200200
- [Two Sum](/algorithm/LeetCode/Array/Two-Sum.md)
201201
- [String](/algorithm/LeetCode/String.md)
202202
- [Restore IP Addresses](/algorithm/LeetCode/String/ip.md)
203+
- [Rotate String](/algorithm/LeetCode/String/Rotate-String.md)
203204

204205
## 设计模式
205206

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
## 一、题目
2+
3+
> Given a string and an offset, rotate string by offset. (rotate from left to right)
4+
>
5+
> Example
6+
>
7+
> Given `"abcdefg"`.
8+
>
9+
> offset=0 => "abcdefg"
10+
> offset=1 => "gabcdef"
11+
> offset=2 => "fgabcde"
12+
> offset=3 => "efgabcd"
13+
>
14+
> Challenge
15+
>
16+
> Rotate in-place with O(1) extra memory.
17+
18+
给定一个字符串和一个偏移量,根据偏移量旋转字符串(从左向右旋转)
19+
20+
## 二、解题思路
21+
22+
常见的翻转法应用题,仔细观察规律可知翻转的分割点在从数组末尾数起的offset位置。先翻转前半部分,随后翻转后半部分,最后整体翻转。
23+
24+
## 三、解题代码
25+
26+
```java
27+
public class Solution {
28+
/*
29+
* param A: A string
30+
* param offset: Rotate string with offset.
31+
* return: Rotated string.
32+
*/
33+
public char[] rotateString(char[] A, int offset) {
34+
if (A == null || A.length == 0) {
35+
return A;
36+
}
37+
38+
int len = A.length;
39+
offset %= len;
40+
reverse(A, 0, len - offset - 1);
41+
reverse(A, len - offset, len - 1);
42+
reverse(A, 0, len - 1);
43+
44+
return A;
45+
}
46+
47+
private void reverse(char[] str, int start, int end) {
48+
while (start < end) {
49+
char temp = str[start];
50+
str[start] = str[end];
51+
str[end] = temp;
52+
start++;
53+
end--;
54+
}
55+
}
56+
}
57+
```
58+

0 commit comments

Comments
 (0)