lintcode :Reverse Words in a String 翻转字符串

题目:

给定一个字符串,逐个翻转字符串中的每个单词。

样例

给出s = "the sky is blue",返回"blue is sky the"

说明
  • 单词的构成:无空格字母构成一个单词
  • 输入字符串是否包括前导或者尾随空格?可以包括,但是反转后的字符不能包括
  • 如何处理两个单词间的多个空格?在反转字符串中间空格减少到只含一个

解题:

这个题目方法很多的

1.整体反转,对每个单词再反转,但是中间的多个空格还有单独处理

2.把后面的单词,拿到前面去。参考程序

Java程序:

public class Solution {
    /**
     * @param s : A string
     * @return : A string
     */
    public String reverseWords(String s) {
        // write your code
        if(s==null || s.length() == 0)
            return "";
        String[] array = s.split(" ");
        StringBuilder sb = new StringBuilder();
        for(int i = array.length - 1;i>=0 ;--i){
            if(!array[i].equals("")){
                sb.append(array[i]).append(" ");
            }
        }
        return sb.length()==0?"":sb.substring(0,sb.length() - 1);
    }
}
View Code

总耗时: 1929 ms

网站今天增加好几道新题,然后我提交一次Pending。。。

Python程序:

class Solution:
    # @param s : A string
    # @return : A string
    def reverseWords(self, s):
        # write your code here
        begin = 0 
        end = 0 
        while end< len(s):
            if s[end] == ' ':
                self.swap(s,begin,end - 1)
                begin = end + 1
                end = begin 
            else:
                end += 1
            # print s 
        self.swap(s,begin,end - 1)
        # print s
        self.swap(s,0,len(s) - 1)
        # print s 
        return s 
                
    def swap(self,s,begin,end):
        while begin< end:
            tmp = s[begin]
            s[begin] = s[end]
            s[end] = tmp
            begin +=1
            end -=1
View Code

这个程序有点问题,没有解决的。。。

原文地址:https://www.cnblogs.com/theskulls/p/4889686.html