当前位置:网站首页>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();
}
}
边栏推荐
猜你喜欢
随机推荐
备忘一下jvxetable的各种数据集获取方法
Force buckle 1189 Maximum number of "balloons"
Fuzzy -- basic application method of AFL
03. 开发博客项目之登录
Compilation and connection of shader in games202 webgl (learn from)
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
Ad20 is set with through-hole direct connection copper sheet, and the bonding pad is cross connected
算法-- 爬楼梯(Kotlin)
Vulhub vulnerability recurrence 73_ Webmin
idea一键导包
Oracle query table index, unique constraint, field
Yyds dry inventory SSH Remote Connection introduction
A little knowledge of CPU, disk and memory
[untitled]
Easy to understand I2C protocol
04. 项目博客之日志
HAC cluster modifying administrator user password
pix2pix:使用条件对抗网络的图像到图像转换
05. 博客项目之安全
从0到1建设智能灰度数据体系:以vivo游戏中心为例
![[effective Objective-C] - memory management](/img/1e/611aa998486bbac76ac103c3091794.jpg)



![[untitled]](/img/7e/d0724193f2f2c8681a68bda9e08289.jpg)




