字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
示例 1:
输入: s = "abcdefg", k = 2
输出: "cdefgab"
示例 2:
输入: s = "lrloseumgh", k = 6
输出: "umghlrlose"
思路1:substring(起点(包含),终点(不包含))
public class reverseleftwords {
public String reverseLeftWords(String s, int n) {
StringBuilder stringBuilder = new StringBuilder();
int slength = s.length();
stringBuilder.append(s.substring(n, slength)).append(s.substring(0, n));
String result = stringBuilder.toString();
return result;
}
}
思路2:原版写的有点啰嗦,可以直接看简化版,(i+n)%slength,避免二次for循环
简化版:
public class reverseleftwords {
public String reverseLeftWords(String s, int n) {
StringBuilder stringBuilder = new StringBuilder();
int slength = s.length();
for (int i = 0; i < slength; i++) {
stringBuilder.append(s.charAt((i+n)%slength));
}
String result = stringBuilder.toString();
return result;
}
}
原版:
public class reverseleftwords {
public String reverseLeftWords(String s, int n) {
StringBuilder stringBuilder = new StringBuilder();
int slength = s.length();
for (int i = n&slength; i < slength; i++) {
stringBuilder.append(s.charAt(i));
}
for (int i = 0; i < n%slength; i++) {
stringBuilder.append(s.charAt(i));
}
String result = stringBuilder.toString();
return result;
}
}