当前位置:网站首页>【日常訓練--騰訊精選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"));
}
}
边栏推荐
- STM32 summary (HAL Library) - DHT11 temperature sensor (intelligent safety assisted driving system)
- 剑指 Offer 05. 替换空格
- Keil use details -- magic wand
- GEO数据库中搜索数据
- 每日一题——替换空格
- 亿学学堂给的证券账户安不安全?哪里可以开户
- Explore the authentication mechanism of StarUML
- Business modeling of software model | stakeholders
- Affected tree (tree DP)
- Arduino+a4988 control stepper motor
猜你喜欢
随机推荐
Lori remote control LEGO motor
2022.7.4-----leetcode. one thousand and two hundred
Various types of questions judged by prime numbers within 100 (C language)
Search data in geo database
Stm32--- systick timer
Bluebridge cup internet of things basic graphic tutorial - GPIO output control LD5 on and off
实例003:完全平方数 一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
Example 005: three numbers sorting input three integers x, y, Z, please output these three numbers from small to large.
Some pitfalls of win10 network sharing
猜谜语啦(8)
Chapter 18 using work queue manager (1)
C language data type replacement
Agile project management of project management
实例002:“个税计算” 企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.
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
OC and OD gate circuit
99 multiplication table (C language)
STM32 --- NVIC interrupt
猜谜语啦(3)
Installation and use of libjpeg and ligpng