当前位置:网站首页>剑指 Offer 58 - I. 翻转单词顺序
剑指 Offer 58 - I. 翻转单词顺序
2022-07-27 07:26:00 【ThE wAlkIng D】
题目描述
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. “,则输出"student. a am I”。

问题解析
本题使用双指针的方法进行遍历
s.trim()方法去除空格键,让i,j从尾部开始遍历当i遍历到空格的时候,使用substring进行截取,把单词截取出来放到res新建StringBuilder后面,最终使用tostring转换成字符串。
代码实例
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
public String reverseWords(String s) {
public String reverseWords(String s) {
s = s.trim();
int i = s.length() - 1;
int j = i;
StringBuilder res = new StringBuilder();
while(i >= 0){
while(i >= 0 && s.charAt(i) != ' '){
i--;
}
res.append(s.substring(i + 1,j + 1) + ' ');
while(i >= 0 && s.charAt(i) == ' '){
i--;
}
j = i;
}
return res.toString().trim();
}
}
}
边栏推荐
- Closed hash and open hash resolve hash conflicts
- DEMO:PA30 银行国家码默认CN 增强
- Multithreading [preliminary - Part 1]
- The DrawImage method calls the solution of not displaying pictures for the first time
- An open source OA office automation system
- Understanding and learning of node flow and processing flow in io
- Regular expression foundation sorting
- Plato farm is expected to further expand its ecosystem through elephant swap
- How to get DDL information of an object
- Flink de duplication (I) summary of common de duplication schemes in Flink and Flink SQL
猜你喜欢

ADC噪声全面分析 -02- ADC 噪声测量方法和相关参数

What about idea Chinese garbled code
![[stonedb class] introductory lesson 1: popular science of database knowledge](/img/ec/4e3c0b91ac2ee164595c2891b23dfb.jpg)
[stonedb class] introductory lesson 1: popular science of database knowledge

Understanding and learning of properties class and properties configuration file

我是不是被代码给耽误了……不幸沦为一名程序员……
![Multithreading [preliminary - Part 1]](/img/e6/5808bbdb8368bc780bde4c151e7cd7.png)
Multithreading [preliminary - Part 1]

Plato farm is expected to further expand its ecosystem through elephant swap

Actual combat of flutter - Request encapsulation (I)

LeetCode56. 合并区间

DEMO SUBMIT 某程序并获取该程序ALV数据
随机推荐
Comprehensive analysis of ADC noise-02-adc noise measurement method and related parameters
Comprehensive analysis of ADC noise-01-types of ADC noise and ADC characteristics
Graylog 日志服务器单节点部署
shell awk相关练习
什么是真正的 HTAP ?(二)挑战篇
Codeforces Round #810 (Div.2) A-C
flink去重(二)解决flink、flink-sql去重过程中的热点问题
Bingbing's learning notes: classes and objects (middle)
帮个忙呗~不关注不登录,不到一分钟的一个问卷
flink去重(一)flink、flink-sql中常见的去重方案总结
Flink principle (I) TTL management and fault tolerance mechanism of state
shell 函数和数组练习
[golang learning notes 2.0] arrays and slices in golang
View the dmesg log before server restart
面试复盘五
【StoneDB Class】入门第一课:数据库知识科普
Using soci to connect Oracle with PostgreSQL and SQLite on rhel8
Flink de duplication (I) summary of common de duplication schemes in Flink and Flink SQL
ADC噪声全面分析 -01- ADC噪声的类型以及ADC特性
【pytorch】ResNet18、ResNet20、ResNet34、ResNet50网络结构与实现