当前位置:网站首页>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();
}
}
边栏推荐
- Graduation design game mall
- Vulhub vulnerability recurrence 71_ Unomi
- C Advanced - data storage (Part 1)
- Questions d'examen écrit classiques du pointeur
- Principle and performance analysis of lepton lossless compression
- February 12 relativelayout
- Simple understanding of interpreters and compilers
- 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
- MySQL if and ifnull use
- MySQL advanced learning summary 9: create index, delete index, descending index, and hide index
猜你喜欢
Using stopwatch to count code time
04. Project blog log
[untitled]
[effective Objective-C] - memory management
Safe mode on Windows
剑指 Offer II 039. 直方图最大矩形面积
Steady, 35K, byte business data analysis post
Please wait while Jenkins is getting ready to work
Fiddler installed the certificate, or prompted that the certificate is invalid
Pix2pix: image to image conversion using conditional countermeasure networks
随机推荐
Detailed summary of SQL injection
UCF (summer team competition II)
Imperial cms7.5 imitation "D9 download station" software application download website source code
Mongodb basic knowledge summary
UCF(暑期团队赛二)
F12 solve the problem that web pages cannot be copied
[classic example] binary tree recursive structure classic topic collection @ binary tree
Huawei equipment is configured with OSPF and BFD linkage
RT thread analysis log system RT_ Kprintf analysis
Summary of redis basic knowledge points
Unity Vector3. Use and calculation principle of reflect
Rce code and Command Execution Vulnerability
Idea one key guide package
In 2022, we must enter the big factory as soon as possible
剑指 Offer II 039. 直方图最大矩形面积
Summary of deep learning tuning tricks
Three methods of Oracle two table Association update
Collection + interview questions
SQLite queries the maximum value and returns the whole row of data
【华为机试真题详解】统计射击比赛成绩