We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
#include<iostream>#include<vector>usingnamespacestd;#define SUBSTR_SZ 3 // Substring sizeclassStack{private:vector<string>_stack_vec;int_top;public:Stack(){_top=-1;}voidpop(){if(!is_empty()){_top=_top-1;_stack_vec.pop_back();return;}else{std::cout<<"Could not retrieve data, stack is empty\n";}return;}voidpush(string_str){_top+=1;_stack_vec.push_back(_str);}stringget_top(){return_stack_vec[_top];}intis_empty(){return!_stack_vec.size();}intstack_size(){return_top+1;}};intmain(){Stackstack;// string _str = "tactactictactictictac"; // validstring_str="tactictac";// invalid// first to label whether the first tic is metboolvalid=true,first=false;for(inti=0;i<_str.size();i=i+SUBSTR_SZ){string_substr=_str.substr(i,SUBSTR_SZ);if(i==0&&_substr=="tic"){valid=false;break;}if(stack.is_empty()&&_substr=="tac"){stack.push(_substr);continue;}if(!stack.is_empty()){if(_substr=="tac")stack.push(_substr);else{if(stack.get_top()=="tic"){valid=false;break;}else{// When not meeting the first tac, with current// top is "tac", pop it outif(!first){stack.pop();// The first tic is met: tac tac ticif(!stack.is_empty()&&stack.get_top()=="tac"){first=true;stack.pop();continue;}elsevalid=false;}elsestack.push(_substr);}}}}std::cout<<valid<<"\n";return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Forward References
You are viewing a single comment's thread. Return to all comments →
This problem can also be solved by stack