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. Sqlserver 安装

    安装环境: SqlServer版本:Sql Server 2008 (安装包您应该已有准备) =============以下开始安装,多图,基本软件操作不做太多说明,注意查看图片=========== ...

  2. clock_gettime的使用,计时比clock()精确

    函数"clock_gettime"是基于Linux C语言的时间函数,可以用于计算时间,有秒和纳秒两种精度. 函数原型: int clock_gettime(clockid_t c ...

  3. Java parseInt_使用此方法得到的原始数据类型的一个特定的字符串

    Java parseInt解释加方法示例     使用此方法得到的原始数据类型的一个特定的字符串. parseXxx()是一个静态方法,可以有一个参数或两个         java parseInt ...

  4. 40个Java集合面试问题和答案【中】【转载】

    接上文:http://www.cnblogs.com/xujianbo/p/5148075.html   16.UnsupportedOperationException是什么? Unsupporte ...

  5. ASP.NET Web API——选择Web API还是WCF

    WCF是.NET平台服务开发的一站式框架,那么为什么还要有ASP.NET Web API呢?简单来说,ASP.NET Web API的设计和构建只考虑了一件事情,那就是HTTP,而WCF的设计主要是考 ...

  6. C# 匿名类型

    c#3.0引入匿名类型,其由编译器动态生成而非显式定义. using System;using System.Collections.Generic;using System.Linq;using S ...

  7. [leetcode] 400. Nth Digit

    https://leetcode.com/contest/5/problems/nth-digit/ 刚开始看不懂题意,后来才理解是这个序列连起来的,看一下第几位是几.然后就是数,1位数几个,2位数几 ...

  8. 安卓Handler机制的例子

    Handler机制是实现线程之间通讯的一种很常见的方法,很多时候都会用到. package com.lab.activity; import android.app.Activity; import ...

  9. hdu 5014 Number Sequence

    为了a异或b的和最大,只需另b在不大于n的情况下按位取反即可. 这里有两个输出小技巧可以参考: 1.在用printf输出__int64时,在windows下使用格式"%I64d", ...

  10. memcached完全剖析--1

    memcached的基础 翻译一篇技术评论社的文章,是讲memcached的连载.fcicq同学说这个东西很有用,希望大家喜欢. 发表日:2008/7/2 作者:长野雅广(Masahiro Nagan ...