[LeetCode] Reverse Words in a String

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 thisString object both have codes greater than '\u0020' (the space character), then a reference to thisString object is returned.

    Otherwise, if there is no character with a code greater than '\u0020' in the string, then a newString 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 ofthis.substring(km+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);
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值