Basic implementation. C++. Understandable code

programming
interview-questions
facebook
Tags: #<Tag:0x00007f2426a3bf50> #<Tag:0x00007f2426a3bd98> #<Tag:0x00007f2426a3bc30>

#1

NOTE: make sure to use ‘\t’ and not ’ ’ or " ". Will save your time of debugging -
Any queries are welcomed -

vector<string> Solution::prettyJSON(string str) {
vector<string> ans;
string temp = "";
int cnt = 0;
for(int i = 0; i < (int)str.size(); i++) {
    if(str[i] == ' ') continue;
    else if(str[i] == '{') {
        ans.push_back(temp);
        ans[(int)ans.size() - 1].push_back('{');
        cnt++;
        temp += '\t';
    }
    else if(str[i] == '[') {
        ans.push_back(temp);
        ans[(int)ans.size() - 1].push_back('[');
        cnt++;
        temp += '\t';
    }
    else if(str[i] == '}') {
        temp = "";
        cnt--;
        for(int j = 0; j < cnt; j++) temp += '\t';
        ans.push_back(temp);
        ans[(int)ans.size() - 1].push_back('}');
    }
    else if(str[i] == ']') {
        temp = "";
        cnt--;
        for(int j = 0; j < cnt; j++) temp += '\t';
        ans.push_back(temp);
        ans[(int)ans.size() - 1].push_back(']');
    }
    else if(str[i] == ',') {
        ans[(int)ans.size() - 1].push_back(str[i]);
    }
    else {
        ans.push_back(temp);
        while(str[i] != '{' && str[i] != '}' && str[i] != '[' && str[i] != ']' && str[i] != ',') {
            ans[(int)ans.size() - 1].push_back(str[i]);
            i++;
        }
        i--;
    }
}
return ans;

}


#2

Can you please help with step by step algorithm for this code, so that it becomes easy to understand.