当前位置:网站首页>【剑指 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();//转化为字符串并且返回
}
}
边栏推荐
- 近视:摘镜or配镜?这些问题必须先了解清楚
- Svn usage specification
- 什么是质押池,如何进行质押呢?
- Rk3399 platform development series explanation (WiFi) 5.54. What is WiFi wireless LAN
- Visual SLAM algorithms: a survey from 2010 to 2016
- How can technology managers quickly improve leadership?
- Mb10m-asemi rectifier bridge mb10m
- Initial test of scikit learn Library
- [combinatorics] combinatorial identities (sum of variable terms 3 combinatorial identities | sum of variable terms 4 combinatorial identities | binomial theorem + derivation to prove combinatorial ide
- Pyinstaller is not an internal or external command, nor is it a runnable program or batch file
猜你喜欢

arduino-esp32:LVGL项目(一)整体框架

斑马识别成狗,AI犯错的原因被斯坦福找到了

First knowledge of database

One article takes you to understand machine learning

Slam learning notes - build a complete gazebo multi machine simulation slam from scratch (III)

From "zero sum game" to "positive sum game", PAAS triggered the third wave of cloud computing

Record windows10 installation tensorflow-gpu2.4.0

Slam learning notes - build a complete gazebo multi machine simulation slam from scratch (I)

NSQ source code installation and operation process

Mysql 单表字段重复数据取最新一条sql语句
随机推荐
切入点表达式
From "zero sum game" to "positive sum game", PAAS triggered the third wave of cloud computing
爱可可AI前沿推介(7.3)
ThreeJS 第二篇:顶点概念、几何体结构
为抵制 7-Zip,列出 “三宗罪” ?网友:“第3个才是重点吧?”
探索Cassandra的去中心化分布式架构
8 cool visual charts to quickly write the visual analysis report that the boss likes to see
Pyinstaller is not an internal or external command, nor is it a runnable program or batch file
Caching mechanism of Hibernate / session level caching mechanism
Unity project optimization case 1
Record a jar package conflict resolution process
Pointcut expression
How programming apes grow rapidly
SVN使用规范
EditText request focus - EditText request focus
Nifi from introduction to practice (nanny level tutorial) - flow
Mixlab编辑团队招募队友啦~~
相同切入点的抽取
PHP CI (CodeIgniter) log level setting
Client does not support authentication protocol requested by server; consider upgrading MySQL client