2019-11-02 12:07:41 +08:00
|
|
|
|
# 58.2 左旋转字符串
|
|
|
|
|
|
|
|
|
|
[NowCoder](https://www.nowcoder.com/practice/12d959b108cb42b1ab72cef4d36af5ec?tpId=13&tqId=11196&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
|
|
|
|
|
|
|
|
|
## 题目描述
|
|
|
|
|
|
|
|
|
|
```html
|
|
|
|
|
Input:
|
|
|
|
|
S="abcXYZdef"
|
|
|
|
|
K=3
|
|
|
|
|
|
|
|
|
|
Output:
|
|
|
|
|
"XYZdefabc"
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
## 解题思路
|
|
|
|
|
|
|
|
|
|
先将 "abc" 和 "XYZdef" 分别翻转,得到 "cbafedZYX",然后再把整个字符串翻转得到 "XYZdefabc"。
|
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
public String LeftRotateString(String str, int n) {
|
|
|
|
|
if (n >= str.length())
|
|
|
|
|
return str;
|
|
|
|
|
char[] chars = str.toCharArray();
|
|
|
|
|
reverse(chars, 0, n - 1);
|
|
|
|
|
reverse(chars, n, chars.length - 1);
|
|
|
|
|
reverse(chars, 0, chars.length - 1);
|
|
|
|
|
return new String(chars);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void reverse(char[] chars, int i, int j) {
|
|
|
|
|
while (i < j)
|
|
|
|
|
swap(chars, i++, j--);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void swap(char[] chars, int i, int j) {
|
|
|
|
|
char t = chars[i];
|
|
|
|
|
chars[i] = chars[j];
|
|
|
|
|
chars[j] = t;
|
|
|
|
|
}
|
|
|
|
|
```
|
2019-11-02 14:39:13 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2019-11-02 17:33:10 +08:00
|
|
|
|
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>
|