当前位置:网站首页>[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;
}
}
边栏推荐
- How to delete "know this picture" on win11 desktop
- Galaxy Kirin system LAN file sharing tutorial
- AI 绘画极简教程
- Method of reading file contents by Excel
- SQL必需掌握的100个重要知识点:用通配符进行过滤
- GBase 8a OLAP分析函数cume_dist的使用样例
- Go from entry to practice -- CSP concurrency mechanism (note)
- Have time to look at ognl expressions
- 小王的面试训练任务
- Knowledge sorting of exception handling
猜你喜欢

SQL必需掌握的100个重要知识点:排序检索数据

Full record of 2022 open source moment at Huawei partners and Developers Conference

CORBA 架构体系指南(通用对象请求代理体系架构)

富文本 考试 填空题

跟我一起AQS SOS AQS

Icml2022 | scalable depth Gaussian Markov random field

What is the core competitiveness of front-line R & D personnel aged 35~40 in this position?

Go从入门到实战——仅执行一次(笔记)

vmware虚拟机PE启动

Here are 12 commonly used function formulas for you. All used ones are good
随机推荐
Special training of guessing game
Go从入门到实战——协程机制(笔记)
Go from introduction to practice - polymorphism (note)
Go从入门到实战——依赖管理(笔记)
Go from introduction to actual combat - all tasks completed (notes)
富文本 考试 填空题
Express e stack - small items in array
Go从入门到实战——package(笔记)
SQL必需掌握的100个重要知识点:用通配符进行过滤
Here are 12 commonly used function formulas for you. All used ones are good
TreeSet详解
Go从入门到实战——所有任务完成(笔记)
The difference between scrum and Kanban
Codeforces Round #723 (Div. 2)
今晚战码先锋润和赛道第2期直播丨如何参与OpenHarmony代码贡献
Go from introduction to practice -- coordination mechanism (note)
win11桌面出現“了解此圖片”如何删除
Method of reading file contents by Excel
White whoring red team goby & POC, how do you call white whoring?
IO stream code