So, the buggy judging system of python is unbearable, therefore I just turned to C++ and expected a better experience. Also, I need to learn C++ for my future career. So, a good start. This post contains following problems:
Reverse words
Eval RPN
Tree Traversal
Reverse words
Before solving this problem I never tried using std::string, I thought string operation in C++ is as hard as C. However, standard library really ease my pains. In fact, with the help of std, I think coding with C++ is much more easier and happier than coding with Ruby and Python now.
Question:
Given an input string, reverse the string word by word.
Basic logic:
The idea is simple, find each word in the sentence, push then in the stack and pop back after dealing the whole sentence. Be careful to the spaces in the head or tails of the sentence and the repeated spaces.
classSolution{public:voidreverseWords(string&s){// get the words in reverse ordervector<string>words;split(s,' ',words);// reconstructs="";if(words.size()==0)return;for(inti=0;i<words.size();i++){s.append(words[i]);s.append(" ");}// delete last spaces.erase(s.length()-1,-1);}voidsplit(string&s,charc,vector<string>&v){intbegin,last;// first wordbegin=s.length()-1;last=s.find_last_of(c,begin);if(s.substr(last+1,begin-last)!=""){v.push_back(s.substr(last+1,begin-last));}// find next wordswhile(last>0andbegin!=-1){// find a word begin=last-1;last=s.find_last_of(c,begin);// if it's repeated split character, skip itwhile(last==begin){begin=last-1;last=s.find_last_of(c,begin);}// skip if is last spaceif(s.substr(last+1,begin-last)!=""){v.push_back(s.substr(last+1,begin-last));}}}};
evalRPN
Question:
Evaluate the value of an arithmetic expression in Reverse Polish Notation. For example:
[“2”, “1”, “+”, “3”, “*”] -> ((2 + 1) * 3) -> 9
Basic logic:
Also simple idea: Iterater through the list, push numbers to a stack. Everytime we meet operaor, pop top 2 numbers and calculate the result, push the result to the stack. Finally, there will be only one number in the stack, which is the reuslt.