From a66e2251c0e053438c6e15057021df7d1b44e375 Mon Sep 17 00:00:00 2001 From: Jidong Xiao Date: Sat, 11 Nov 2023 21:53:04 -0500 Subject: [PATCH] adding two stack problems --- leetcode/p20_valid_parentheses.cpp | 37 ++++++++++++++++++++++++++++++ leetcode/p71_simplify_path.cpp | 30 ++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 leetcode/p20_valid_parentheses.cpp create mode 100644 leetcode/p71_simplify_path.cpp diff --git a/leetcode/p20_valid_parentheses.cpp b/leetcode/p20_valid_parentheses.cpp new file mode 100644 index 0000000..3e7f055 --- /dev/null +++ b/leetcode/p20_valid_parentheses.cpp @@ -0,0 +1,37 @@ +class Solution { +public: + bool isValid(string s) { + std::stack myStack; + int len = s.length(); + char c; + for(int i=0;i myStack; + // convert path to a string stream, and split it by the delimiter '/'. + stringstream ss(path); + while(getline(ss, item, '/')){ + if(item == ".."){ + if(!myStack.empty()){ + myStack.pop(); + } + }else if(item != "." && item != ""){ + // we only push valid items into the stack + myStack.push(item); + } + } + // since we were given an absolute path, which starts with a slash, if at this moment the stack is empty, it means either we didn't push anything into the stack, or everything is popped out. + if(myStack.empty()){ + return "/"; + } + std::string result = ""; + // now let's concatenate all valid items. + while(!myStack.empty()){ + result = "/" + myStack.top() + result; + myStack.pop(); + } + return result; + } +};