LeetCode 557. Reverse Words in a String III (反转字符串中的单词 III)
2024-08-31 01:07:03
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
题目标签:String
题目给了我们一串string,让我们把每一个word 给reverse一下。
设p1 和 p2,每一次让p2 找到 “ ” space,然后 reverse p1 和 p2 之间的 word,然后更新p1 和 p2 的值。
具体请看code。
Java Solution:
Runtime beats 96.43%
完成日期:05/31/2018
关键词:Two pointers
关键点:反转p1 和 p2 之间的 word
class Solution
{
public String reverseWords(String s)
{
char [] arr = s.toCharArray();
int p1 = 0;
int p2 = 0; while(p1 < arr.length)
{
// let p2 find the space
while(p2 < arr.length && arr[p2] != ' ')
p2++; // once p2 find the space, do reverse between p1 and p2
int left = p1;
int right = p2 - 1; while(left < right)
{
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp; left++;
right--;
} // reset p1 p2
p1 = p2 + 1;
p2++; } return new String(arr);
} }
参考资料:n/a
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/
最新文章
- Scala基础语法 (一)
- JavaScript的个人学习随手记(三)
- 【SAP BO】BOE 4.1版本新特性
- spring-session整合
- Java Hour 30 Weather ( 3 )
- 针对应用程序池“xxxxxx”的模板永久性缓存初始化失败,解决方法
- 转:三十一、Java图形化界面设计——布局管理器之GridLayout(网格布局)
- JavaScriptSerializer类 对象序列化为JSON,JSON反序列化为对象
- Handler和HandlerThread
- vs调试时底部输出调试信息“无法查找或打开 PDB 文件”解决办法
- Page-Object设计模式
- 老李分享:android手机测试之适配(2)
- NOIP 2017 day -1 杂记
- 金蝶K3外购入库单单价取数规则调整
- Python进制表示及转换
- C++进阶--逻辑常数和比特位常数(Logical constness vs Bitwise constness)
- Hello 2018 A,B,C,D
- TL 重构
- 转:Java中String与byte[]的转换
- JavaScript数组(参考资料)