当前位置:网站首页>【日常訓練--騰訊精選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 007: copy data from one list to another list.

Explore the authentication mechanism of StarUML

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

剑指 Offer 09. 用两个栈实现队列

猜谜语啦(10)

Guess riddles (2)

MATLAB小技巧(28)模糊綜合評價

STM32 summary (HAL Library) - DHT11 temperature sensor (intelligent safety assisted driving system)

Arduino operation stm32

猜谜语啦(2)
随机推荐
猜谜语啦(5)
【三层架构及JDBC总结】
Guess riddles (11)
Lori remote control commissioning record
关于线性稳压器的五个设计细节
STM32---ADC
Brief discussion on Buck buck circuit
Agile project management of project management
STM32 summary (HAL Library) - DHT11 temperature sensor (intelligent safety assisted driving system)
实例009:暂停一秒输出
MATLAB小技巧(28)模糊綜合評價
2020-05-21
Business modeling of software model | vision
[three tier architecture and JDBC summary]
Is the security account given by Yixue school safe? Where can I open an account
MySQL MHA high availability cluster
關於線性穩壓器的五個設計細節
Various types of questions judged by prime numbers within 100 (C language)
Xrosstools tool installation for X-Series
Example 005: three numbers sorting input three integers x, y, Z, please output these three numbers from small to large.