当前位置:网站首页>LeetCode_字符串反转_简单_557. 反转字符串中的单词 III
LeetCode_字符串反转_简单_557. 反转字符串中的单词 III
2022-07-06 05:23:00 【小城老街】
1.题目
给定一个字符串 s ,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。
示例 1:
输入:s = “Let’s take LeetCode contest”
输出:“s’teL ekat edoCteeL tsetnoc”
示例 2:
输入: s = “God Ding”
输出:“doG gniD”
提示:
1 <= s.length <= 5 * 104
s 包含可打印的 ASCII 字符。
s 不包含任何开头或结尾空格。
s 里至少有一个词。
s 中的所有单词都用一个空格隔开。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/reverse-words-in-a-string-iii
2.思路
(1)字符串反转
3.代码实现(Java)
//思路1————字符串反转
class Solution {
public String reverseWords(String s) {
StringBuffer res = new StringBuffer();
int length = s.length();
int i = 0;
while (i < length) {
//记录当前单词的起点下标
int index = i;
//找到当前单词的终点下标
while (i < length && s.charAt(i) != ' ') {
i++;
}
//反转当前单词
for (int j = index; j < i; j++) {
res.append(s.charAt(i - j - 1 + index));
}
//保留单词之间的空格
while (i < length && s.charAt(i) == ' ') {
i++;
res.append(' ');
}
}
return res.toString();
}
}
边栏推荐
- Set detailed map + interview questions
- Promotion hung up! The leader said it wasn't my poor skills
- Ad20 is set with through-hole direct connection copper sheet, and the bonding pad is cross connected
- The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
- 从0到1建设智能灰度数据体系:以vivo游戏中心为例
- February 12 relativelayout
- C进阶-数据的存储(上)
- Sword finger offer II 039 Maximum rectangular area of histogram
- 【华为机试真题详解】统计射击比赛成绩
- Safe mode on Windows
猜你喜欢

pix2pix:使用条件对抗网络的图像到图像转换

Talking about the type and function of lens filter

Nacos TC setup of highly available Seata (02)

Principle and performance analysis of lepton lossless compression

04. 项目博客之日志
![[leetcode] 18. Sum of four numbers](/img/06/c160b47d756290e5474e4c07e68648.png)
[leetcode] 18. Sum of four numbers

Check the useful photo lossless magnification software on Apple computer

Pointer classic written test questions

Steady, 35K, byte business data analysis post

Vite configures the development environment and production environment
随机推荐
趋势前沿 | 达摩院语音 AI 最新技术大全
2022半年总结
自建DNS服务器,客户端打开网页慢,解决办法
JS quick start (II)
Excel转换为Lua的配置文件
Vulhub vulnerability recurrence 72_ uWSGI
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
UCF (summer team competition II)
04. 项目博客之日志
[leetcode] 18. Sum of four numbers
02. 开发博客项目之数据存储
Postman Association
Pagoda configuration mongodb
Compilation and connection of shader in games202 webgl (learn from)
Leetcode dynamic planning day 16
备忘一下jvxetable的各种数据集获取方法
February 12 relativelayout
Mongodb basic knowledge summary
【LeetCode】18、四数之和
Ora-01779: the column corresponding to the non key value saving table cannot be modified