loga vignesh
loga vignesh

Reputation: 3

Reverse Words in a String , I do not know why I am getting this output

class Solution {
public:
    string reverseWords(string s) {
        int n=s.size();
        
        string p;
        vector<string> arr;
        
        
        for (int i=0;i<n;i++){
            p=p+s[i];
            if (to_string(s[i]) == " "){
                arr.push_back(p);
                p = "";
            }
            if (i==n-1){
                arr.push_back(p);
                break;
            }
        }
        string q;
        int m=arr.size();
        for (int j=m-1;j>=0;j--){
            q=q+arr[j];
        }
        
        return q;
        
    }
};
Wrong Answer
Runtime: 0 ms
Your input
"the sky is blue"
Output
"the sky is blue"
Expected
"blue is sky the"

Upvotes: 0

Views: 60

Answers (1)

Yksisarvinen
Yksisarvinen

Reputation: 22394

std::to_string() is a function which converts a number to std::string. Since no number can ever be represented as " " (a string containing a single space), your condition is never true.

Change your condition to

if (s[i] == ' ')

to compare characters.

Upvotes: 3

Related Questions