Getting run time error for more than 3 words.


  • 0
    P

    I just edited my solution of Reverse words in a string. Getting right answer for words less than 4

    class Solution {
    public:
         void reverse(string &str, int start,int end)
        {
            while(start<=end)
                swap(str[start++],str[end--]);
        }
        string reverseWords(string s) {
    
    
            int idx=0;
            string str="";
            //reverse(s,0,s.size()-1);
            
            for(int i=0;i<s.size();i++)
            {
                if(s[i]!=' ')
                {
                    if(idx!=0) str[idx++]=' ';
                    int j=i;
                    for(;j<s.size() && s[j]!=' ';){  
                        str[idx++]=s[j++];
                }
                    reverse(str,idx-(j-i),idx-1);
                    i=j;
                }
            }
            str[idx]='\0';
            return str;
        }
            
        
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.