方法一:字符串切片(时间复杂度O(N))
返回两个拼接在一起的子字符串
public String reverseLeftWords(String s, int n) {
return s.substring(n, s.length()) + s.substring(0, n);
}
方法二:列表遍历拼接(时间复杂度O(N))
新建字符串列表 ,将字符串按条件添加
public String reverseLeftWords(String s, int n) {
StringBuilder res = new StringBuilder();
for(int i = n; i < s.length(); i++)
res.append(s.charAt(i));
for(int i = 0; i < n; i++)
res.append(s.charAt(i));
return res.toString();
}
方法三:字符串遍历拼接(时间复杂度O(N))
区别于方法二,这里新建字符串。效率低下,每轮都要新建字符串。
public String reverseLeftWords(String s, int n) {
String res = "";
for(int i = n; i < s.length(); i++)
res += s.charAt(i);
for(int i = 0; i < n; i++)
res += s.charAt(i);
return res;
}