当前位置:网站首页>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();
}
}
边栏推荐
- HAC集群修改管理员用户密码
- Three.js学习-光照和阴影(了解向)
- 浅谈镜头滤镜的类型及作用
- 关于Unity Inspector上的一些常用技巧,一般用于编辑器扩展或者其他
- Fiddler installed the certificate, or prompted that the certificate is invalid
- Pointer classic written test questions
- Collection + interview questions
- 關於Unity Inspector上的一些常用技巧,一般用於編輯器擴展或者其他
- 【torch】|torch.nn.utils.clip_grad_norm_
- 02. 开发博客项目之数据存储
猜你喜欢
Easy to understand I2C protocol
[cloud native] 3.1 kubernetes platform installation kubespher
Nacos TC setup of highly available Seata (02)
Lepton 无损压缩原理及性能分析
从0到1建设智能灰度数据体系:以vivo游戏中心为例
浅谈镜头滤镜的类型及作用
【torch】|torch.nn.utils.clip_grad_norm_
Huawei equipment is configured with OSPF and BFD linkage
Notes, continuation, escape and other symbols
Microblogging hot search stock selection strategy
随机推荐
nacos-高可用seata之TC搭建(02)
Class inheritance in yyds dry inventory C
Pix2pix: image to image conversion using conditional countermeasure networks
改善Jpopup以实现动态控制disable
Vulhub vulnerability recurrence 73_ Webmin
Knowledge points of circular structure
Force buckle 1189 Maximum number of "balloons"
Set detailed map + interview questions
Huawei od computer test question 2
Graduation design game mall
C Advanced - data storage (Part 1)
Fiddler installed the certificate, or prompted that the certificate is invalid
[cloud native] 3.1 kubernetes platform installation kubespher
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
In 2022, we must enter the big factory as soon as possible
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
jdbc使用call调用存储过程报错
[leetcode daily question] number of enclaves
Postman assertion
關於Unity Inspector上的一些常用技巧,一般用於編輯器擴展或者其他