File tree Expand file tree Collapse file tree 2 files changed +59
-0
lines changed
algorithm/LeetCode/String Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Original file line number Diff line number Diff line change 200
200
- [ Two Sum] ( /algorithm/LeetCode/Array/Two-Sum.md )
201
201
- [ String] ( /algorithm/LeetCode/String.md )
202
202
- [ Restore IP Addresses] ( /algorithm/LeetCode/String/ip.md )
203
+ - [ Rotate String] ( /algorithm/LeetCode/String/Rotate-String.md )
203
204
204
205
## 设计模式
205
206
Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments