p155 翻转单词顺序(leetcode 151)

一:解题思路

C++: Time:O(n) Space:O(1)

Java:Time:O(n) Space:O(n)

二:完整代码示例 (C++版和Java版)

C++:

C++和Java一样的代码,但是C++不能全部AC,这个有点不太理解,还是把代码贴出来了。

class Solution
{
private:
    void reverse(string& sc, int i, int j)
    {
        for (; i < j; i++, j--)
        {
            char temp = sc[i];
            sc[i] = sc[j];
            sc[j] = temp;
        }
    }
public:
    string reverseWords(string s)
    {
        if (s.length() == 0) return s;
        int p = 0;
        int q = 0;
        int end = s.length() - 1;
        while (end >= 0 && s[end] == ' ') end--;

        while (q <= end)
        {
            int start = p;
            while (q <= end && s[q] == ' ') q++;
            while (q <= end && s[q] != ' ') s[p++] = s[q++];
            reverse(s, start, p - 1);
            
            if (q <= end) s[p++] = ' ';
        }

        reverse(s, 0,p - 1);

        return s;
    }
};

Java:

class Solution
    {
        private void reverse(char[] sc,int i,int j)
        {
            for(;i<j;i++,j--)
            {
                char temp=sc[i];
                sc[i]=sc[j];
                sc[j]=temp;
            }
        }
        
        public String reverseWords(String s) 
        {
               if(s==null || s.length()==0) return s;
               char[] str=s.toCharArray();
               int p=0;
               int q=0;
               int end=s.length()-1;
               while(end>=0 && s.charAt(end)==' ') end--;
               
               while(q<=end)
               {
                   int start=p;
                   while(q<=end && s.charAt(q)==' ') q++;
                   while (q<=end && s.charAt(q)!=' ') str[p++]=str[q++];
                   reverse(str,start,p-1);
                   if(q<=end) str[p++]=' ';
               }
               
               reverse(str,0,p-1);
               
               return new String(str,0,p);
        }
    }
上一篇:猫猫和他的朋友们(第一卷 151-180)


下一篇:C++ 编程中最基本和最常见的 I/O 操作。突然进入即可撒