您的位置:首页 > 其它

[LeetCode] Reverse Words in a String

2014-05-14 04:36 489 查看
Given an input string, reverse the string word by word.

For example,

Given s = "
the sky is blue
",

return "
blue is sky the
".

click to show clarification.

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.

java实现
public String reverseWords(String s) {
        String newString = s.trim();
		if(newString.length()<=0) return s.trim();
		String []splitsStrings = newString.split(" ");
		int len = splitsStrings.length;
		StringBuilder sBuilder = new StringBuilder("");
		for(int i=len-1;i>=0;i--){
			if(splitsStrings[i].length()>0){
				sBuilder.append(splitsStrings[i]);
				sBuilder.append(" ");
			}
		}
		String resultString = sBuilder.toString();
		return resultString.trim();
    }


public String trim()

Returns a copy of the string, with leading and trailing whitespace omitted.
If this
String
object represents an empty character sequence, or the first and last characters of character sequence represented by this
String
object both have codes greater than
'\u0020'
(the space character), then a reference to this
String
object is returned.

Otherwise, if there is no character with a code greater than
'\u0020'
in the string, then a new
String
object representing an empty string is created and returned.

Otherwise, let k be the index of the first character in the string whose code is greater than
'\u0020'
, and let
m be the index of the last character in the string whose code is greater than
'\u0020'
. A new
String
object is created, representing the substring of this string that begins with the character at indexk and ends with the character at index
m-that is, the result of
this.substring(k, m+1)
.

This method may be used to trim whitespace (as defined above) from the beginning and end of a string.

Returns:A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

StringBuilder

public StringBuilder(String str)

Constructs a string builder initialized to the contents of the specified string. The initial capacity of the string builder is
16
plus the length of the string argument.
Parameters:
str
- the initial contents of the buffer. Throws:
NullPointerException
- if
str
is
null


C++


Analysis:

The clarification is very important, during the interview, one should think of these points without hint, and then implement the algorithm.

By checking the clarifications, the programming is straightforward, here provides a simple version which uses buffer strings:

(1)Loop from start to the end of the string:

(a) if current char is space and word string is empty, continue.

(b) if current char is space but word string is NOT empty, which means we meet the end of word, then output the word, reset the word, continue.

(c) if current char is non-space char, add this char to the word string, continue

(2)Handle the last word:

(a) if the last word is empty, which means the input is empty, or the input has only spaces, or the last char/chars are spaces. Then just remove the last space in the output string and return.

(b) if the last word is not empty, add the last word to the front of the output string, then remove the last space in the output string and return.

void reverseWords(string &s) {
    string word;//tmp string to store each word
    string res;// result string
    int i = 0;
    for(int i=0;i<s.size();i++){
        if(s[i]==' ' && word.empty()) continue;//multiple spaces
        if(s[i]==' ' && !word.empty()){// word ends
            res = word+" "+res;// add word to result string
            word = "";// reset the word
            continue;
        }
        if(s[i]!=' '){//non space characters
            word.push_back(s[i]);
            continue;
        }
    }
    if(!word.empty())//last word
        s = word+" "+res;
    else
        s = res;
    s = s.substr(0,s.size()-1);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: