死磕算法系列文章
“Leetcode : https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/
“GitHub : https://github.com/nateshao/leetcode/blob/main/algo-notes/src/main/java/com/nateshao/sword_offer/topic_46_reverseLeftWords/Solution.java
“题目描述 :字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。 难度:简单
示例 1:
输入: s = "abcdefg", k = 2
输出: "cdefgab"
示例 2:
输入: s = "lrloseumgh", k = 6
输出: "umghlrlose"
获取字符串 s[ n : ] 切片和 s[ : n ]切片,使用 "+" 运算符拼接并返回即可。
复杂度分析:
package com.nateshao.sword_offer.topic_46_reverseLeftWords;
/**
* @date Created by 邵桐杰 on 2022/2/20 19:46
* @微信公众号 千羽的编程时光
* @个人网站 www.nateshao.cn
* @博客 https://nateshao.gitee.io
* @GitHub https://github.com/nateshao
* @Gitee https://gitee.com/nateshao
* Description:
*/
public class Solution {
public static void main(String[] args) {
String s = "abcdefg";
System.out.println("reverseLeftWords1(s,2) = " + reverseLeftWords1(s, 2));// reverseLeftWords1(s,2) = cdefgab
}
/**
* 方法一:字符串切片
* @param s
* @param n
* @return
*/
public static String reverseLeftWords1(String s, int n) {
return s.substring(n, s.length()) + s.substring(0, n);
}
}
“若面试规定不允许使用 切片函数 ,则使用此方法。
/**
* 方法二:列表遍历拼接
*/
public static String reverseLeftWords2(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();
}
此方法与方法二思路一致,区别是使用字符串代替列表。
复杂度分析:
public String reverseLeftWords3(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;
}
参考链接:https://leetcode-cn.com/problems/zuo-xuan-zhuan-zi-fu-chuan-lcof/solution/mian-shi-ti-58-ii-zuo-xuan-zhuan-zi-fu-chuan-qie-p