写bug之前我就知道这样偷懒有问题,结果i++就放错了地方。
我以后不 有意识的写bug了。
把原来的代码 把重复的代码 用函数去表示后, 我华为的第三题就出来了。
立贴,以后别偷懒。。
#include<iostream> #include<string> #include<stack> #include<unordered_map> #include<vector> using namespace std; int doSometing(string str); void single(stack<int>& st_num, stack<char>& st_syl, string& str, int i){ int help = st_num.top(); st_num.pop(); help = !help; st_num.push(help); st_syl.pop(); st_syl.push(str[i]); } void two(stack<int>& st_num, stack<char>& st_syl, string& str, int i){ int l1 = st_num.top(); st_num.pop(); int l2 = st_num.top(); st_num.pop(); l1 = l1 & l2; st_num.push(l1); st_syl.pop(); st_syl.push(str[i]); } int main(){ char arr[1000]; // cin.getline(arr,1000); // string str = arr; // cout << doSometing(str); cout << doSometing("((!0&1))|((0))"); return 0; } int doSometing(string str){ int i=0; stack<char> st_syl; stack<int> st_num; stack<int> st_kuo;// 存括号的位置 // cout << "begin : str :" << str <<endl; while(i<str.size()){ // cout << "i :" << i << " value " << str[i] <<endl; if(str[i] == '('){ st_kuo.push(i); i++; }else if(str[i] == ')'){ cout << endl; cout << "*********************"<<endl<<endl;; int pos = st_kuo.top(); st_kuo.pop(); int length = i - pos +1 - 2; string next_str = str.substr(pos+1, length); cout << "old_str : " << str << endl; cout << "recur_str : " << next_str << endl; int ans = doSometing(next_str); cout << "recur_answer is " << ans <<endl; // cout << "length is : " << length << endl; // cout << "now i ----> " << i <<endl; str.replace(pos, length+2, to_string(ans)); // 重叠括号情况 cout << "new_str : " << str << endl; st_num.push(ans); i = i - length; }else{ if(!st_kuo.empty()){ i++; }else{ if(str[i]=='!'|| str[i]=='&'|| str[i]=='|'){ // 是字符 if(st_syl.empty()){ st_syl.push(str[i]); }else{ if(st_syl.top() == '!'){ single(st_num, st_syl, str, i); }else if(st_syl.top() == '&' && (str[i] == '|' || str[i] == '&&')){ two(st_num, st_syl, str, i); }else if(st_syl.top() == '|' && str[i] == '|'){ two(st_num, st_syl, str, i); }else{ st_syl.push(str[i]); } } i++; }else{ // 是‘’数字 st_num.push(str[i]-'0'); i++; } } } } while(!st_syl.empty()){ char c = st_syl.top(); st_syl.pop(); if(c == '!'){ int help = st_num.top(); st_num.pop(); help = !help; st_num.push(help); }else{ int l1 = st_num.top(); st_num.pop(); int l2 = st_num.top(); st_num.pop(); if(c == '&'){ l1 = l1 & l2; }else{ l1 = l1 | l2; } st_num.push(l1); } } return st_num.top(); }