当前位置:网站首页>[LeetCode]186. 翻转字符串里的单词 II
[LeetCode]186. 翻转字符串里的单词 II
2022-06-27 19:35:00 【阿飞算法】
题目
题目描述
给定一个字符串,逐个翻转字符串中的每个单词。
示例:
输入: ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
输出: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]
注意:
单词的定义是不包含空格的一系列字符
输入字符串中不会包含前置或尾随的空格
单词与单词之间永远是以单个空格隔开的
进阶:
使用 O(1) 额外空间复杂度的原地解法
作者:珺王不早朝
链接:https://www.jianshu.com/p/9d624882d786
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
方法1:翻转
public void reverseWords(char[] str) {
int i = 0;
for (int j = 0; j < str.length; j++) {
if (str[j] == ' ') {
reverse(str, i, j);
i = j + 1;
}
}
reverse(str, i, str.length);
System.out.println(String.valueOf(str));
reverse(str, 0, str.length);
}
/** * 将 ch 的 [l, r] 进行翻转, * 注意,[l,r) 是左闭右开 * * @param ch * @param l * @param r */
private void reverse(char[] ch, int l, int r) {
for (int k = l; k < (l + r) / 2; k++) {
char tmp = ch[k]; // 位置 k 的元素
int g = r - 1 - k + l; // 位置 k 的对称位置
ch[k] = ch[g];
ch[g] = tmp;
}
}
边栏推荐
- 安装gatewayworker之后启动start.php
- Can Oracle's CTAs bring constraints and other attributes to the new table?
- Go从入门到实战——CSP并发机制(笔记)
- Process control task
- What is the core competitiveness of front-line R & D personnel aged 35~40 in this position?
- Scrum和看板的区别
- Go从入门到实战——多态(笔记)
- Yu Wenwen, Hu Xia and other stars take you to play with the party. Pipi app ignites your summer
- 富文本 考试 填空题
- 根据自定义excel标题模板快速excel导出
猜你喜欢

Modify large online games through CE modifier

猜拳游戏专题训练

Go from introduction to practice - Interface (notes)

win11桌面出现“了解此图片”如何删除

Go从入门到实战——channel的关闭和广播(笔记)

At 19:00 on Tuesday evening, the 8th live broadcast of battle code Pioneer - how to participate in openharmony's open source contribution in multiple directions

抖音的兴趣电商已经碰到流量天花板?

强制 20 天内开发 APP 后集体被裁,技术负责人怒批:祝“早日倒闭!”

洛谷P5706 再分肥宅水

MySQL performance optimization index function, hidden, prefix, hash index usage (2)
随机推荐
CEPH distributed storage
Go from starting to Real - Interface (note)
专题教程——选队长游戏
SQL必需掌握的100个重要知识点:检索数据
Yu Wenwen, Hu Xia and other stars take you to play with the party. Pipi app ignites your summer
Go从入门到实战——仅需任意任务完成(笔记)
Is it safe to open an account and buy stocks? Who knows
猜拳游戏专题训练
流程控制任务
富文本 考试 填空题
Kirin V10 installation font
Codeforces Round #716 (Div. 2)
微服务之远程调用
本周二晚19:00战码先锋第8期直播丨如何多方位参与OpenHarmony开源贡献
MySQL performance optimization index function, hidden, prefix, hash index usage (2)
Magic POI error in reading excel template file
Go from introduction to practice - polymorphism (note)
SQL必需掌握的100个重要知识点:使用函数处理数据
Codeforces Round #723 (Div. 2)
GBase 8a V8版本节点替换期间通过并发数控制资源使用减少对系统影响的方法