当前位置:网站首页>leetcode刷题:字符串05(剑指 Offer 58 - II. 左旋转字符串)
leetcode刷题:字符串05(剑指 Offer 58 - II. 左旋转字符串)
2022-06-26 20:31:00 【涛涛英语学不进去】
题目:剑指Offer58-II.左旋转字符串
字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
示例 1:
输入: s = “abcdefg”, k = 2
输出: “cdefgab”
示例 2:
输入: s = “lrloseumgh”, k = 6
输出: “umghlrlose”
限制:
1 <= k < s.length <= 10000
这题一拿上来,这需要脑子?
public String reverseLeftWords1(String s, int n) {
//截取当前字符串前左n位
String head = s.substring(0, n);
return s.substring(n) + head;
}

再看看题解
按题解的思路再做一遍。
public String reverseLeftWords(String s, int n) {
StringBuilder result = new StringBuilder(s);
//反转前半段
reverseStr(result, 0, n);
//反转后半段
reverseStr(result, n, s.length());
//反转整段
reverseStr(result, 0, s.length());
return String.valueOf(result);
}
/** * 反转指定区间内字符串 * * @param s * @param start * @param end * @return */
public static StringBuilder reverseStr(StringBuilder s, int start, int end) {
while (start < end) {
char temp = s.charAt(start);
s.setCharAt(start, s.charAt(end - 1));
s.setCharAt(end-1, temp);
start++;
end--;
}
return s;
}

有一说一,不看题解是真想不到可以这样做。
边栏推荐
- 开发者调查:Rust/PostgreSQL 最受喜爱,PHP 薪水偏低
- Uni app uses canvas to draw QR code
- 0 basic C language (0)
- 网上办理中金财富开户安全吗?
- What are the specific steps for opening a stock account? Is it safe to open an account online?
- When are global variables initialized before entering the main function?
- 【贝叶斯分类3】半朴素贝叶斯分类器
- 论数据库的传统与未来之争之溯源溯本----AWS系列专栏
- 【最详细】最新最全Redis面试大全(70道)
- ImageView, glide load long picture (glide load picture)
猜你喜欢

Muke 8. Service fault tolerance Sentinel

The relationship between the development of cloud computing technology and chip processor

Selection of database paradigm and main code
Mongodb implements creating and deleting databases, creating and deleting tables (sets), and adding, deleting, modifying, and querying data
Detailed explanation of stored procedures in MySQL

Gee: calculate the maximum and minimum values of pixels in the image area

IDEA 报错:Process terminated【已解决】

mongoDB的三种基础备份方法

Tiktok practice ~ sharing module ~ copy short video link

Super VRT
随机推荐
定长内存池
好物推荐:移动端开发安全工具
云计算技术的发展与芯片处理器的关系
C primer plus learning notes - 3. Character IO (input / output)
IDEA 报错:Process terminated【已解决】
开发者调查:Rust/PostgreSQL 最受喜爱,PHP 薪水偏低
JWT operation tool class sharing
Summary of several common UML diagrams
抖音实战~分享模块~短视频下载(保存到相册)
两个文件 合并为第三个文件 。
抖音实战~搜索页面~扫描二维码
阿里云个人镜像仓库日常基本使用
西瓜书重温(七): 贝叶斯分类器(手推+代码demo)
C language 99 multiplication table
案例描述:比赛分数管理系统,需要统计历届冠军所得比赛得分,并记录到文件中,其中系统有如下需求:- 打开系统有欢迎界面,并显示可选择的选项- 选项1:记录比赛得分- 选项2:查看往届
Flutter TextField详解
Idea error: process terminated
抖音实战~搜索页面~视频详情
慕课8、服务容错-Sentinel
Unity——Mathf. Similarities and differences between atan and atan2
