当前位置:网站首页>【日常訓練--騰訊精選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"));
}
}
边栏推荐
- Example 005: three numbers sorting input three integers x, y, Z, please output these three numbers from small to large.
- Sword finger offer 05 Replace spaces
- Guess riddles (10)
- STM32 --- GPIO configuration & GPIO related library functions
- 实例003:完全平方数 一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
- leetcode - 445. 两数相加 II
- [three tier architecture]
- MySQL之MHA高可用集群
- Sword finger offer 06 Print linked list from end to end
- UE像素流,来颗“减肥药”吧!
猜你喜欢
随机推荐
Brief discussion on Buck buck circuit
Five design details of linear regulator
The first week of summer vacation
关于线性稳压器的五个设计细节
U8g2 drawing
Example 002: the bonus paid by the "individual income tax calculation" enterprise is based on the profit commission. When the profit (I) is less than or equal to 100000 yuan, the bonus can be increase
MATLAB小技巧(28)模糊綜合評價
轮子1:QCustomPlot初始化模板
Sword finger offer 06 Print linked list from end to end
Agile project management of project management
如何写Cover Letter?
猜谜语啦(5)
Count the number of inputs (C language)
剑指 Offer 06. 从尾到头打印链表
实例004:这天第几天 输入某年某月某日,判断这一天是这一年的第几天?
Bluebridge cup internet of things basic graphic tutorial - GPIO input key control LD5 on and off
Various types of questions judged by prime numbers within 100 (C language)
Bluebridge cup internet of things competition basic graphic tutorial - clock selection
[noi simulation] juice tree (tree DP)
Guess riddles (9)









