当前位置:网站首页>【日常訓練--騰訊精選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"));
}
}
边栏推荐
- 暑假第一周
- MySQL之MHA高可用集群
- 猜谜语啦(8)
- Guess riddles (142)
- STM32 single chip microcomputer -- debug in keil5 cannot enter the main function
- UE pixel stream, come to a "diet pill"!
- Stm32--- systick timer
- STM32 single chip microcomputer -- volatile keyword
- 剑指 Offer 06. 从尾到头打印链表
- Example 005: three numbers sorting input three integers x, y, Z, please output these three numbers from small to large.
猜你喜欢

Lori remote control LEGO motor

MySQL MHA high availability cluster

TypeScript手把手教程,简单易懂

MATLAB skills (28) Fuzzy Comprehensive Evaluation

OC and OD gate circuit

实例010:给人看的时间

Daily question - input a date and output the day of the year

Business modeling of software model | stakeholders

STM32 single chip microcomputer -- debug in keil5 cannot enter the main function

Arduino burning program and Arduino burning bootloader
随机推荐
第十八章 使用工作队列管理器(一)
MySQL MHA high availability cluster
剑指 Offer 05. 替换空格
每日一题——替换空格
Reasons for the insecurity of C language standard function scanf
Example 005: three numbers sorting input three integers x, y, Z, please output these three numbers from small to large.
MySQL之MHA高可用集群
Arduino burning program and Arduino burning bootloader
Run菜单解析
Lori remote control LEGO motor
Guess riddles (8)
Example 001: the number combination has four numbers: 1, 2, 3, 4. How many three digits can be formed that are different from each other and have no duplicate numbers? How many are each?
【三层架构及JDBC总结】
Void* C is a carrier for realizing polymorphism
Lori remote control commissioning record
Business modeling of software model | overview
实例003:完全平方数 一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
99 multiplication table (C language)
Detailed summary of FIO test hard disk performance parameters and examples (with source code)
MySQL之MHA高可用集群