标记现在已经匹配到o1的第几列车了,o2从头开始,如果不匹配把o1就放入栈中,匹配后出栈并比较栈顶与o1的下一辆,匹配继续出,不匹配就继续进栈
1 #include <iostream> 2 #include <string> 3 #include <cstdio> 4 #include <stack> 5 using namespace std; 6 int main() 7 { 8 int n; 9 while (scanf("%d", &n) != EOF) 10 { 11 string o1, o2; 12 cin >> o1 >> o2; 13 stack<int> s; 14 bool flag[1000] = {0}; 15 int i = 0, j = 0, k = 1; //i,j,k分别为O1,O2,result下标 16 s.push(o1[0]); 17 flag[0] = 1; 18 while (i < n && j < n) 19 { 20 if (!s.empty() && s.top() == o2[j]) 21 { 22 s.pop(); 23 flag[k++] = 0; 24 ++j; 25 } 26 else 27 { 28 s.push(o1[++i]); 29 flag[k++] = 1; 30 } 31 } 32 if (i == n) 33 cout << "No." << endl; 34 else 35 { 36 cout << "Yes." << endl; 37 for (int i = 0; i < k; ++i) 38 if (flag[i]) 39 cout << "in" << endl; 40 else 41 cout << "out" << endl; 42 } 43 cout << "FINISH" << endl; 44 } 45 system("pause"); 46 return 0; 47 }