当前位置:网站首页>剑指 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();
}
}
}
边栏推荐
- A priority SQL problem
- linux能不能安装sqlserver
- Top ten interview questions for software testing (with answers and analysis)
- 容器内使用sudo报错bash: sudo: command not found解决
- flink去重(一)flink、flink-sql中常见的去重方案总结
- C language implementation of guessing numbers Games project practice (based on srand function, rand function, switch statement, while loop, if condition criterion, etc.)
- Panabit SNMP configuration
- Shell condition test, judgment statement and operator of shell system learning
- shell企业面试题练习
- Help send a recruitment, base all over the country. If you are interested, you can come and have a look
猜你喜欢

帮忙发一份招聘,base全国,有兴趣的可以过来看看

C winfrom common function integration-2

C language implementation of guessing numbers Games project practice (based on srand function, rand function, switch statement, while loop, if condition criterion, etc.)

Okaleido ecological core equity Oka, all in fusion mining mode

什么是真正的 HTAP ?(二)挑战篇

Okaleido生态核心权益OKA,尽在聚变Mining模式

Installation and use of apifox

STM32_ Find the cause of entering hardfault_ Handler's function

Use Amazon dynamodb and Amazon S3 combined with gzip compression to maximize the storage of player data

linux能不能安装sqlserver
随机推荐
Flink1.14 SQL basic syntax (I) detailed explanation of Flink SQL table query
Record a pit dug by yourself~
An open source OA office automation system
flink原理(一) 状态的TTL管理、容错机制
Gossip: Recently, many friends talk about going abroad
View the dmesg log before server restart
Understanding and learning of properties class and properties configuration file
Chapter 6 Shell Logic and Arithmetic
Using soci to connect Oracle with PostgreSQL and SQLite on rhel8
正则 和 sed 练习
安装tensorflow
帮忙发一份招聘,base全国,有兴趣的可以过来看看
drawImage方法第一次调用不显示图片的解决方式
【Golang】golang开发微信公众号网页授权功能
RPC remote procedure call
什么是真正的HTAP?(一)背景篇
Install tensorflow
SQL statement batch update time minus 1 day
[golang learning notes 2.0] arrays and slices in golang
Summary of several common ways to join dimension tables in Flink