LeetCode Reverse Words in a String II
2016-03-06 03:35
399 查看
原题链接在这里:https://leetcode.com/problems/reverse-words-in-a-string-ii/
题目:
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
题解:
类似Reverse Words in a String. input变成 char array.
先reverse 全部 char array. 从头往后走,遇到空格或者array尾部,就reverse中间的单词.
Time Compelxity: O(n). Space: O(1).
AC Java:
题目:
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 = "
the sky is blue",
return "
blue is sky the".
Could you do it in-place without allocating extra space?
Related problem: Rotate Array
题解:
类似Reverse Words in a String. input变成 char array.
先reverse 全部 char array. 从头往后走,遇到空格或者array尾部,就reverse中间的单词.
Time Compelxity: O(n). Space: O(1).
AC Java:
public class Solution { public void reverseWords(char[] s) { if(s == null || s.length == 0){ return; } reverse(s, 0, s.length-1); int lo = 0; for(int i = 1; i<=s.length; i++){ if(i == s.length || s[i] == ' '){ reverse(s, lo, i-1); lo = i+1; } } } private void reverse(char [] s, int i, int j){ while(i < j){ swap(s, i++, j--); } } private void swap(char [] s, int i , int j){ char temp = s[i]; s[i] = s[j]; s[j] = temp; } }
相关文章推荐
- 64位Ubuntu使用john破解密码的No password hashes loaded
- 关于JAVA中的Synchronization和interface误用
- leetcode50 Pow(x, n)
- 召回率与准确率概念
- LeetCode Range Sum Query 2D - Mutable
- *栈的应用
- 栈[链栈]
- leetcode206 Reverse Linked List
- shell脚本中echo显示内容带颜色
- elasticsearch小记之--sort的type
- Android自定义控件ImageViwe(一)——依据控件的大小来设置缩放图片显示
- unity, destroy gameObject & destroy all children
- 云管端概念
- C#: WMI 获取远程 Windows 主机信息
- opencv2.0 saturate_cast<?> 研究
- 关于两个可移动ViewGroup触摸事件冲突处理
- build、compile、rebuild all
- 碰撞检测之Sphere-Box检测
- [DX9/10.1]在现代硬件上模拟调色板贴图
- 待我长发及腰