当前位置:网站首页>剑指 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
- 电子量产项目框架--基本思想
- Demonstrate the use of foreign keys with Oracle
- Debug:与泛型有关的“无法解析的外部符号”
- C winfrom common function integration-2
- IDEA中文乱码怎么办
- MCU multi-level menu
- 什么是真正的HTAP?(一)背景篇
- Plato Farm有望通过Elephant Swap,进一步向外拓展生态
- 连接MySQL时报错:Public Key Retrieval is not allowed 【解决方法】
猜你喜欢

杂谈:手里有竿儿,肩上有网,至于背篓里有多少鱼真的重要吗?

Zabbix: map collected values to readable statements

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

Okaleido tiger is about to log in to binance NFT in the second round, which has aroused heated discussion in the community

Clickhouse notes 1 | introduction, features | installation and use based on centos7 system | common data types | mergetree table engine | SQL operation

连接MySQL时报错:Public Key Retrieval is not allowed 【解决方法】

Gossip: talk with your daughter about why you should learn culture lessons well

IO中节点流和处理流的理解学习

Properties类和properties配置文件的理解学习

mysql备份策略
随机推荐
[golang learning notes 2.1] sorting and searching in arrays in golang
Record a pit dug by yourself~
User unlock sm04 sm12
模仿大佬制作的宿舍门禁系统(三)
小程序消息推送配置 Token校验失败,请检查确认
Installation and use of apifox
Use Amazon dynamodb and Amazon S3 combined with gzip compression to maximize the storage of player data
闭散列和开散列解决哈希冲突
mysql备份策略
Pg_ relation_ Size question
Cadence(十一)丝印调整和后续事项
Interview reply V
drawImage方法第一次调用不显示图片的解决方式
Showdoc vulnerability learning - cnvd-2020-26585 (arbitrary file upload)
Use Popen to execute a command and get the return result
Plato farm is expected to further expand its ecosystem through elephant swap
记录一个自己挖的坑~
MCU multi-level menu
我是不是被代码给耽误了……不幸沦为一名程序员……
Help send a recruitment, base all over the country. If you are interested, you can come and have a look