题目:
https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/
题解一:
先按照指定长度截断后再拼接。
public String reverseLeftWords(String s, int n) {
String left = s.substring(0, n);
String right = s.substring(n);
return right + left;
}
题解二:
按照给定的数字将字符串分为两部分,先将每部分翻转一次,最后再将整个字符串翻转一次。
public String reverseLeftWords(String s, int n) {
StringBuilder stringBuilder = new StringBuilder(s);
reverseString(stringBuilder, 0, n-1);
reverseString(stringBuilder, n, s.length()-1);
reverseString(stringBuilder, 0, s.length()-1);
return stringBuilder.toString();
}
/**
* 翻转字符串
*
* @param stringBuilder stringBuilder对象
* @param start 字符串起索引
* @param end 字符串止索引
*/
private void reverseString(StringBuilder stringBuilder, int start, int end) {
while (start < end) {
char temp = stringBuilder.charAt(start);
stringBuilder.setCharAt(start, stringBuilder.charAt(end));
stringBuilder.setCharAt(end, temp);
start++;
end--;
}
}