JZ43-左旋转字符串
左旋转字符串
https://www.nowcoder.com/practice/12d959b108cb42b1ab72cef4d36af5ec?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey
/**
* abc cba
* XYZdef fedZYX 相加 cbafedZYX 再反转 XYZdefabc
*/
class Solution2 {
public String LeftRotateString(String str, int n) {
if (str == null || str.length() == 0) {
return str;
}
char[] chars = str.toCharArray();
int realN = n % chars.length;
reverse(chars, 0, realN - 1);
reverse(chars, realN, chars.length - 1);
reverse(chars, 0, chars.length - 1);
return new String(chars);
}
private void reverse(char[] chars, int start, int end) {
while (start < end) {
swap(chars, start, end);
start++;
end--;
}
}
private void swap(char[] chars, int i, int j) {
char temp = chars[i];
chars[i] = chars[j];
chars[j] = temp;
}
} 
