当前位置:网站首页>【日常训练--腾讯精选50】557. 反转字符串中的单词 III
【日常训练--腾讯精选50】557. 反转字符串中的单词 III
2022-07-05 08:36:00 【Puppet__】
题目
给定一个字符串 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 中的所有单词都用一个空格隔开
代码
package tencent50;
public class leetcode557 {
// 使用额外空间,并通过原字符串中的空格将切分为多段,每段进行翻转
public String reverseWords(String s) {
StringBuffer sb = new StringBuffer();
int len = s.length();
int i = 0;
while( i < len){
int start = i;
// 先找空格在哪里
while (i < len && s.charAt(i) != ' '){
i++;
}
// 将单词翻转
for (int j = i - 1; j >= start; j--){
sb.append(s.charAt(j));
}
//跳过之后的空格
while (i < len && s.charAt(i) == ' '){
i++;
sb.append(' ');
}
}
return sb.toString();
}
public static void main(String[] args) {
leetcode557 obj = new leetcode557();
System.out.println(obj.reverseWords("Let's take LeetCode contest"));
}
}
边栏推荐
- Guess riddles (7)
- 關於線性穩壓器的五個設計細節
- Apaas platform of TOP10 abroad
- UE pixel stream, come to a "diet pill"!
- Negative pressure generation of buck-boost circuit
- 实例009:暂停一秒输出
- 轮子1:QCustomPlot初始化模板
- How can fresh students write resumes to attract HR and interviewers
- How to write cover letter?
- Business modeling | process of software model
猜你喜欢
随机推荐
Esphone Feixun DC1 soft change access homeassstant
U8g2 drawing
Illustration of eight classic pointer written test questions
Run菜单解析
Array integration initialization (C language)
猜谜语啦(3)
猜谜语啦(7)
第十八章 使用工作队列管理器(一)
Example 006: Fibonacci series
STM32---ADC
Speech recognition learning summary
Lori remote control commissioning record
UE像素流,来颗“减肥药”吧!
Business modeling of software model | object modeling
Xrosstools tool installation for X-Series
How can fresh students write resumes to attract HR and interviewers
Sword finger offer 09 Implementing queues with two stacks
Bluebridge cup internet of things competition basic graphic tutorial - clock selection
Esphone retrofits old fans
Old Wang's esp8266 and old Wu's ws2818 light strip