当前位置:网站首页>【日常訓練--騰訊精選50】557. 反轉字符串中的單詞 III
【日常訓練--騰訊精選50】557. 反轉字符串中的單詞 III
2022-07-05 08:37: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 (8)
- 2020-05-21
- Installation and use of libjpeg and ligpng
- C language data type replacement
- C语言标准函数scanf不安全的原因
- Detailed summary of FIO test hard disk performance parameters and examples (with source code)
- Bluebridge cup internet of things competition basic graphic tutorial - clock selection
- Infected Tree(树形dp)
- Example 006: Fibonacci series
- 2022.7.4-----leetcode.1200
猜你喜欢

Numpy 小坑:维度 (n, 1) 和 维度 (n, ) 数组相加运算后维度变为 (n, n)

Business modeling of software model | object modeling

Arduino burning program and Arduino burning bootloader

Guess riddles (142)

How apaas is applied in different organizational structures

猜谜语啦(7)

Count the number of inputs (C language)

OC and OD gate circuit

Apaas platform of TOP10 abroad

UE pixel stream, come to a "diet pill"!
随机推荐
轮子1:QCustomPlot初始化模板
UE像素流,来颗“减肥药”吧!
696. 计数二进制子串
猜谜语啦(142)
Lori remote control LEGO motor
STM32 --- serial port communication
亿学学堂给的证券账户安不安全?哪里可以开户
Example 003: a complete square is an integer. It is a complete square after adding 100, and it is a complete square after adding 168. What is the number?
DCDC circuit - function of bootstrap capacitor
Various types of questions judged by prime numbers within 100 (C language)
实例004:这天第几天 输入某年某月某日,判断这一天是这一年的第几天?
猜谜语啦(11)
MySQL MHA high availability cluster
Weidongshan Internet of things learning lesson 1
猜谜语啦(8)
Affected tree (tree DP)
[NAS1](2021CVPR)AttentiveNAS: Improving Neural Architecture Search via Attentive Sampling (未完)
TypeScript手把手教程,简单易懂
287. Looking for repeats - fast and slow pointer
Agile project management of project management