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. oracle里面的时间转字符串to_char(),字符串转时间to_date(),以及substr和instr的使用。

    工作中编写过的一条语句 select * from Bt_Holiday where to_char(Setting_DATE,'YYYY')=Substr('2015-03-00',1,4) AND ...

  2. ###《Machine Learning in Action》 - KNN

    初学Python:理解机器学习. 算法是需要实现的,纸上得来终觉浅. // @author: gr // @date: 2015-01-16 // @email: forgerui@gmail.com ...

  3. ### C++总结-[类成员函数]

    C++类中的常见函数. #@author: gr #@date: 2015-07-23 #@email: forgerui@gmail.com 一.constructor, copy construc ...

  4. 学习C++ Primer 的个人理解(七)

    类,后面还有两章是介绍有关于类的内容的.这一张依然只是个概括.但也已经将大致用法介绍完了. 重点如下: 1.成员函数的声明,必须在类的内部. 2.引用const成员函数 我们知道成员函数中有一个名为t ...

  5. C++(指针)

    指针在编程中有时很重要的作用 我们可以用它完成一些看似不可能完成的任务 #include<iostream>using namespace std;void square(int *n){ ...

  6. Java标准输入输出流的重定向及恢复

    在Java中输入输出数据一般(图形化界面例外)要用到标准输入输出流System.in和System.out,System.in,System.out默认指向控制台,但有时程序从文件中输入数据并将结果输 ...

  7. A Case for Flash Memory SSD in Enterprise Database Applications

    通过分析固态硬盘的特性对数据库中不同对象,如:表,索引,回滚段,重做日志等的应用进行具体研究,最后将数据库中不同的对象进行区别应用

  8. C#基础(六)——值类型与引用类型

    CLR支持两种类型:值类型和引用类型. 值类型包括C#的基本类型(用关键字int.char.float等来声明),结构(用struct关键字声明的类型),枚举(用enum关键字声明的类型):而引用类型 ...

  9. asp.net+MVC--1

    1.MVC入门 1)第一个路由: /*任何应用程序启动时发生的动作都应该存在于单独的类中,并且仅在该方法中按照正确顺序调用*/        protected void Application_St ...

  10. mysql存储过程讲解

    1.数据库存储过程:简单滴说,存储过程就是存储在数据库中的一个程序. 2..数据库存储过程作用: 第一:存储过程因为SQL语句已经预编绎过了,因此运行的速度比较快. 第二:存储过程可以接受参数.输出参 ...