Leetcode Reverse Words in a String II
2015-10-11 03:02
465 查看
Given an input string, reverse the string word by word. A word is defined as a sequence of non-space characters.
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "
return "
Could you do it in-place without allocating extra space?
Related problem: Rotate Array
(1)reverse the whole array
(2)reverse each subarray seperated by ' '
Java code:
Reference:
1. http://www.cnblogs.com/EdwardLiu/p/4306561.html
2. https://leetcode.com/discuss/24227/my-java-solution-with-explanation
The input string does not contain leading or trailing spaces and the words are always separated by a single space.
For example,
Given s = "
the sky is blue",
return "
blue is sky the".
Could you do it in-place without allocating extra space?
Related problem: Rotate Array
解题思路:
和Leetcode Rotate Array 思路一样。(1)reverse the whole array
(2)reverse each subarray seperated by ' '
Java code:
public class Solution { public void reverseWords(char[] s) { reverse(s, 0, s.length-1); int start = 0; for(int i = 0; i< s.length; i++){ if(s[i] == ' '){ reverse(s, start, i-1); start = i+1; } } reverse(s, start, s.length-1); } public void reverse(char[] s, int l, int r){ while(l < r){ char temp = s[l]; s[l] = s[r]; s[r] = temp; l++; r--; } } }
Reference:
1. http://www.cnblogs.com/EdwardLiu/p/4306561.html
2. https://leetcode.com/discuss/24227/my-java-solution-with-explanation
相关文章推荐
- 12家人均创收最高的科技公司
- 【资源共享】香瓜的常用开发资源
- Leetcode Reverse Words in a String
- Ember.js 入门指南——包裹内容
- java传入相关的时间可以获取这个时间段的星期时间
- Android应用开发性能优化完全分析
- 安卓手机烧内存卡(就是内存卡损坏)的补救办法
- 记惠普javaweb实训周之版本控制系统的实践
- MFC库中CObject
- LXT6架构-linux-x/arch/arm/下的故事(回顾)
- Handler+Looper+MessageQueue深入详解
- 深入浅出MFC学习笔记4--简单而完整:MFC骨干程序
- OpenCV3.0.0在VS2013中的配置(Win7_32位)
- EasyUI弹出窗口实例
- ISO/IEC 9899:2011 条款6.7——声明
- 深入探讨Java的类加载机制
- Leetcode Rotate Array
- 数据结构实践项目——串
- Eclipse desktop
- 20151010 C# 第一篇 变量类型