leetcode面试准备:Reverse Words in a String

1 题目

Given an input string, reverse the string word by word.

For example,

Given s = "the sky is blue",

return "blue is sky the".

Update (2015-02-12):

For C programmers: Try to solve it in-place in O(1) space.

2 思路

介绍一种很直接的做法,就是类似于java中String::split函数做的操作,把字符串按空格分开,不过我们把重复的空格直接忽略过去。接下来就是把得到的结果单词反转过来得到结果。因为过程中就是一次扫描得到字符串,然后再一次扫描得出结果,所以时间复杂度是O(n)。空间上要用一个数组来存,所以是O(n)。

  • use split() method,clean up redundancy like "",and then reverse the words.
  • advanced point:regular expression "\\s+" can clean up redundancy blank.
  • attention:if input is " ", the expect output is "". and the code is ok because of split("\s+").

再介绍另一种方法,思路是先把整个串反转并且同时去掉多余的空格,然后再对反转后的字符串对其中的每个单词进行反转,比如"the sky is blue",先反转成"eulb si yks eht",然后在对每一个单词反转,得到"blue is sky the"。这种方法先反转的时间复杂度是O(n),然后再对每个单词反转需要扫描两次(一次是得到单词长度,一次反转单词),所以总复杂度也是O(n),比起上一种方法并没有提高,甚至还多扫描了一次,不过空间上这个不需要额外的存储一份字符串,不过从量级来说也还是O(n)。(用C语言要求实现此方法在O(1)的空间)

我后面用java,测试了一下数组的写法。当练练手,无法通过题目的测试。

3 代码

	/*
* Time:O(n) Space:O(n)
*/
public String reverseWords(String s) {
String[] words = s.trim().split("\\s+");
int size = words.length - 1;
String res = words[size];
for (int i = size - 1; i >= 0; i--) {
res = res + " " + words[i];
}
return res;
}

用数组来体会一下,另外一种思路。

public void reverseWords1(char[] chs) {
int len = chs.length;
// 1.过滤掉前后多余的空格
int left = 0, right = len - 1;
for (int i = 0; i < len && (chs[i] == ' '); i++) {
left++;
}
for (int i = len - 1; i >= 0 && (chs[i] == ' '); i--) {
right--;
}
// System.out.println("left:"+ left + " right:" + right); // 2.过滤掉中间冗余的空格
int newLen = right - left + 1;
int index = 0;
chs[index] = chs[left];
for (int i = left + 1; i <= right; i++) {
if (chs[i] == ' ' && chs[i] == chs[index]) {
continue;
} else {
index++;
chs[index] = chs[i];
// System.out.println(chs[index]);
} }
// System.out.println("newString:" + Arrays.toString(chs)); // 3.反转整个字符串,然后在反转其中的单词。
reverse(chs, 0, newLen - 1);
// System.out.println("newString:" + Arrays.toString(chs));
// System.out.println("newLen:" + newLen);
for (int i = 0, last = 0; i < newLen; i++) {
if ( i == newLen || chs[i] == ' ') {
reverse(chs, last, i - 1);
last = i + 1;
}
}
System.out.println("res:" + Arrays.toString(chs));
}

4 总结

考察字符串的操作。

扩展

Reverse Words in a String II:要求用常量空间。

该题在LeetCode中假设开头和结尾没有空格,而且单词之间只有一个空格。但其实不需要这些假设也是可以的,就是代码会比较复杂。

思路就是两步走,第一步就是将整个字符串翻转。然后从头逐步扫描,将每个遇到单词再翻转过来。

注意事项

1)如果是Java,应该跟面试官指出String是immutable,所以需要用char array来做。

2)follow-up问题:k-step reverse。也就是在第二部翻转的时候,把k个单词看作一个长单词,进行翻转。

leetcode面试准备:Reverse Words in a String的更多相关文章

  1. 【leetcode】557. Reverse Words in a String III

    Algorithm [leetcode]557. Reverse Words in a String III https://leetcode.com/problems/reverse-words-i ...

  2. 【LeetCode OJ】Reverse Words in a String

    Problem link: http://oj.leetcode.com/problems/reverse-words-in-a-string/ Given an input string, reve ...

  3. 【LeetCode】151. Reverse Words in a String

    Difficulty: Medium  More:[目录]LeetCode Java实现 Description Given an input string, reverse the string w ...

  4. 【LeetCode练习题】Reverse Words in a String

    Reverse Words in a String Given an input string, reverse the string word by word. For example,Given ...

  5. 【leetcode】345. Reverse Vowels of a String

    problem 345. Reverse Vowels of a String class Solution { public: string reverseVowels(string s) { , ...

  6. 【刷题-LeetCode】151 Reverse Words in a String

    Reverse Words in a String Given an input string, reverse the string word by word. Example 1: Input: ...

  7. 【一天一道LeetCode】#345. Reverse Vowels of a String

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Write a ...

  8. LeetCode算法题-Reverse Words in a String III(Java实现)

    这是悦乐书的第259次更新,第272篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第126题(顺位题号是557).给定一个字符串,您需要反转句子中每个单词中的字符顺序,同 ...

  9. 【LeetCode】345. Reverse Vowels of a String 解题报告(Java & Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 使用栈 双指针 日期 [LeetCode] 题目地址 ...

随机推荐

  1. CDN的原理及对SEO的影响

    http://www.williamlong.info/archives/4059.html CDN的概念最早于1995年由美国麻省理工大学提出,是一套能够实现用户就近访问的网络解决方案.具体方法是: ...

  2. sql标准化的后缀

    今天在SQL编码风格中看到的sql编码标准

  3. C++例题练习(2)

    环境:Dev-C++( Version:5.6.1) 1.循环输入一个1-1000的整数,判断是否为素数(输入1时程序结束) 素数:只能被1和自身整除. 实现代码: #include <iost ...

  4. Ext.Net学习笔记22:Ext.Net Tree 用法详解

    Ext.Net学习笔记22:Ext.Net Tree 用法详解 上面的图片是一个简单的树,使用Ext.Net来创建这样的树结构非常简单,代码如下: <ext:TreePanel runat=&q ...

  5. Podfile 文件的编写

    # Uncomment this line to define a global platform for your projectplatform :ios, '9.0' target 'Cocoa ...

  6. enum 与 #define

    enum 与 #define 一.为什么既要有enum,又要define enum is derived from enumerate, from ex- + number,字面意思就是用数字排列,报 ...

  7. sgu 107 987654321 problem

    其实挺水的,因为两个数平方,只有固定的后面几位数会影响到最后结果的后面几位数.也就是说,如果想在平方之后尾数为987654321,那么就有固定的几个尾数在平方后会是这个数,打个表,发现 10^8 内 ...

  8. Jquery Offset, Document, Window 都是什么

    From http://www.cnblogs.com/luhe/archive/2012/11/14/2769263.html   JQuery Offset实验与应用 我们有时候需要实现这样一种功 ...

  9. [python]使用ElementTree解析XML【译】

    19.7 The ElementTree XML API 源码:Lib/xml/etree/ElementTree.py Element类型是一个灵活的容器对象,设计出来是用于存储有层次的数据结构到内 ...

  10. Python Socket,How to Create Socket Server? - 网络编程实例

    文章出自:Python socket – network programming tutorial by Silver Moon 原创译文,如有版权问题请联系删除. Network programin ...