当前位置:网站首页>leetcode 剑指 Offer 58 - I. 翻转单词顺序
leetcode 剑指 Offer 58 - I. 翻转单词顺序
2022-07-30 08:52:00 【kt1776133839】
题目描述:
输入一个英文句子,翻转句子中单词的顺序,但单词内字符的顺序不变。为简单起见,标点符号和普通字母一样处理。例如输入字符串"I am a student. ",则输出"student. a am I"。
样例:
示例 1:
输入: "the sky is blue"
输出: "blue is sky the"
示例 2:
输入: " hello world! "
输出: "world! hello"
解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
示例 3:
输入: "a good example"
输出: "example good a"
解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
说明:
无空格字符构成一个单词。
输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。
如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。
解题思路:
双指针
倒序遍历字符串 sss ,记录单词左右索引边界 iii , jjj ;
每确定一个单词的边界,则将其添加至单词列表 resresres ;
最终,将单词列表拼接为字符串,并返回即可。
Java程序:
class Solution {
public String reverseWords(String s) {
s = s.trim(); // 删除首尾空格
int j = s.length() - 1, i = j;
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; // j 指向下个单词的尾字符
}
return res.toString().trim(); // 转化为字符串并返回
}
}
边栏推荐
- leetcode-990:等式方程的可满足性
- 02-课程发布
- Field interpretation under "Surgical variables (RX SUMM-SURG OTH REG/DIS)" in SEER database
- 信号完整性测试
- MySQL [operator]
- HashSet and LinkedHashSet
- Apache DolphinScheduler's new generation of distributed workflow task scheduling platform in practice - Part 1
- Functional Interfaces & Lambda Expressions - Simple Application Notes
- 研发转至FAE(现场应用工程师),是否远离技术了?有前途吗?
- Integral Topic Notes - Path Independent Conditions
猜你喜欢
随机推荐
ClickHouse
Devops和低代码的故事:螳螂捕蝉,黄雀在后
【无标题】
Unreal Engine Graphic Notes: could not be compiled. Try rebuilding from source manually. Problem solving
TreeSet parsing
积分专题笔记-与路径无关条件
BaseQuickAdapter方法getBindingAdapterPosition
使用 Neuron 接入 Modbus TCP 及 Modbus RTU 协议设备
SRAM与DRAM的区别
Use the R language to read the csv file into a data frame, and then view the properties of each column.
20220728 Use the bluetooth on the computer and the bluetooth module HC-05 of Huicheng Technology to pair the bluetooth serial port transmission
Liunx服务器安装SVN(安装包版)
内卷下的智能投影行业,未来何去何从?
MySQL [operator]
Detailed description of iperf3 parameter options
如何避免CMDB沦为数据孤岛?
HCIP - MPLS VPN experiment
MySQL Explain usage and parameter detailed explanation
百度paddleocr检测训练
九九乘法表









