adding two stack problems
This commit is contained in:
37
leetcode/p20_valid_parentheses.cpp
Normal file
37
leetcode/p20_valid_parentheses.cpp
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
bool isValid(string s) {
|
||||||
|
std::stack<char> myStack;
|
||||||
|
int len = s.length();
|
||||||
|
char c;
|
||||||
|
for(int i=0;i<len;i++){
|
||||||
|
// push all the open brackets into the stack
|
||||||
|
if(s[i]=='(' || s[i]=='{' || s[i]=='['){
|
||||||
|
myStack.push(s[i]);
|
||||||
|
}else{
|
||||||
|
// if we encounter a close bracket first, it's already invalid.
|
||||||
|
if(myStack.empty()){
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
c = myStack.top();
|
||||||
|
myStack.pop();
|
||||||
|
// for every close bracket we encounter, there must be a corresponding open bracket at the top of the stack.
|
||||||
|
if(s[i]==')' && c!='('){
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if(s[i]=='}' && c!='{'){
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if(s[i]==']' && c!='['){
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// if it's empty, we are good.
|
||||||
|
if(myStack.empty()){
|
||||||
|
return true;
|
||||||
|
}else{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
30
leetcode/p71_simplify_path.cpp
Normal file
30
leetcode/p71_simplify_path.cpp
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
string simplifyPath(string path) {
|
||||||
|
std::string item;
|
||||||
|
std::stack<string> 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;
|
||||||
|
}
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user