Tuesday, August 5, 2014

Reverse Words in a string@leetcode

Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue",
return "blue is sky the".
Clarification:
  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.
Have you been asked this question in an interview?

The algorithm for this problem is easy to come up with. We can just reverse every single words in the string, then reverse the whole string. However, we got to take care of the corner cases. For example, the beginning and tail are spaces and only one space is allowed between words. So we have to reduce the spaces if there are more than just one and to take care of the spaces in both begin and end.

Be aware that, using char *s and string. The elements in container string is const char, we can't convert the elements in char *s to string. Also, the operations of string container are mostly  work for string, but not single elements.

Here, we need to use, string.push_back(), reverse(s.begin(), s.end()), append(str).

Javascript to crack the string manipulation is very neat. Here is the code.

If you are new to JS, you might need to know a few basic JS functions.

1. split() : to split a string into substrings and you will need to define a separator for it.
For example, str.split(' '); str = "Hello World!" split string is an array which is [Hello, World!].

2. filter() : filter is to filter a string due to some rules. And the rules is defined by a function in it. filter(Boolean) is used to filter falsy, null etc. elements.

3. join() : to join the substrings together as a string with something. 

1 comment:

  1. 写的比我好,空间使用差不多,但我是用栈做的,就麻烦好多,关于char和char*早看到就好了

    ReplyDelete

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...