Algorithm
스택_백준_키로거_5397
MoYoungmin
2018. 8. 15. 14:20
이 문제는 백준 #1406 문제와 비슷하게 풀 수 있다. 커서를 기준으로 왼/오른쪽 스택을 두어 처리 할 수있다. 이 문제 역시 시간복잡도는 O(N)이다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | #include <iostream> #include <string> #include <stack> using namespace std; int main() { int count; string input; stack <char> leftStack; stack <char> rightStack; int length = 0; cin >> count; for (int k = 0; k < count; k++) { cin >> input; length = input.size(); for (int i = 0; i < length; i++) { if (input[i] == '<') { if (leftStack.empty()) { continue; } // exception handling rightStack.push(leftStack.top()); leftStack.pop(); } else if (input[i] == '>') { if (rightStack.empty()) { continue; } // exception handling leftStack.push(rightStack.top()); rightStack.pop(); } else if (input[i] == '-') { if (leftStack.empty()) { continue; } // exception handling leftStack.pop(); } else { leftStack.push(input[i]); } }//calculate while (!leftStack.empty()) { rightStack.push(leftStack.top()); leftStack.pop(); } while (!rightStack.empty()) { cout << rightStack.top(); rightStack.pop(); } cout << endl; //print } return 0; } | cs |