当前位置:网站首页>【剑指 Offer】58 - I. 翻转单词顺序
【剑指 Offer】58 - I. 翻转单词顺序
2022-07-03 16:29:00 【LuZhouShiLi】
剑指 Offer 58 - I. 翻转单词顺序
题目
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. “,则输出"student. a am I”。
思路
双指针,倒叙遍历字符串s,记录单词左右索引边界i,j。每次确定一个单词的边界,就将其添加到单词列表res中,最终,将单词列表拼接为字符串,并返回即可。
代码
class Solution {
public String reverseWords(String s) {
s = s.trim();// 删除首尾空格
int j = s.length() - 1,i = j;
StringBuilder res = new StringBuilder();
// 从后往前搜索
// "hello world"
while(i >= 0)
{
while(i >= 0 && s.charAt(i) != ' ') i--;// 搜索首个空格 遇到空格i停止搜索
// 分割字符串 从i + 1开始不是空格 然后到j位置(j+1取不到)
res.append(s.substring(i + 1,j + 1) + " ");// 添加单词
while(i >= 0 && s.charAt(i) == ' ')
{
i--;// 跳过单词间空格
}
// 更新j 然后下一步接着移动i
j = i;
}
return res.toString().trim();//转化为字符串并且返回
}
}
边栏推荐
- A survey of state of the art on visual slam
- [redis foundation] understand redis persistence mechanism together (rdb+aof graphic explanation)
- Chinese translation of Tagore's floating birds (1~10)
- Slam learning notes - build a complete gazebo multi machine simulation slam from scratch (II)
- 无心剑中译泰戈尔《漂鸟集(1~10)》
- 爱可可AI前沿推介(7.3)
- 中南大学|通过探索理解: 发现具有深度强化学习的可解释特征
- 【声明】关于检索SogK1997而找到诸多网页爬虫结果这件事
- Netease UI automation test exploration: airtest+poco
- First knowledge of database
猜你喜欢
Add color to the interface automation test framework and realize the enterprise wechat test report
Mysql 单表字段重复数据取最新一条sql语句
[proteus simulation] 8 × 8LED dot matrix screen imitates elevator digital scrolling display
Slam learning notes - build a complete gazebo multi machine simulation slam from scratch (II)
QT串口ui设计和解决显示中文乱码
Colab works with Google cloud disk
From "zero sum game" to "positive sum game", PAAS triggered the third wave of cloud computing
A survey of state of the art on visual slam
[redis foundation] understand redis persistence mechanism together (rdb+aof graphic explanation)
斑馬識別成狗,AI犯錯的原因被斯坦福找到了
随机推荐
Record a jar package conflict resolution process
Slam learning notes - build a complete gazebo multi machine simulation slam from scratch (4)
[combinatorics] summary of combinatorial identities (eleven combinatorial identities | proof methods of combinatorial identities | summation methods)*
Record windows10 installation tensorflow-gpu2.4.0
初试scikit-learn库
用通达信炒股开户安全吗?
Explore Cassandra's decentralized distributed architecture
PHP CI(CodeIgniter)log级别设置
Famous blackmail software stops operation and releases decryption keys. Most hospital IOT devices have security vulnerabilities | global network security hotspot on February 14
NFT新的契机,多媒体NFT聚合平台OKALEIDO即将上线
Cocos Creator 2.x 自动打包(构建 + 编译)
Getting started with Message Oriented Middleware
探索Cassandra的去中心化分布式架构
Cocos Creator 2. X automatic packaging (build + compile)
在ntpdate同步时间的时候出现“the NTP socket is in use, exiting”
Leetcode binary search tree
2022爱分析· 国央企数字化厂商全景报告
Mixlab编辑团队招募队友啦~~
香港理工大学|数据高效的强化学习和网络流量动态的自适应最优周界控制
[redis foundation] understand redis persistence mechanism together (rdb+aof graphic explanation)