首页 > 学院 > 开发设计 > 正文

20. Valid Parentheses / 71. Simplify Path

2019-11-10 18:49:42
字体:
来源:转载
供稿:网友

Valid Parentheses题目描述代码实现Simplify Path题目描述代码实现

20. Valid Parentheses

题目描述

括号匹配:

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

代码实现

class Solution {public: bool isValid(string s) { int s_len = s.size(); stack<char> tmp; for(int i = 0; i < s_len; i++) { if(s[i] == '(' || s[i] == '{' || s[i] == '[') { tmp.push(s[i]); } else { if(tmp.empty()) return false; char t = tmp.top(); tmp.pop(); if(s[i] == ')' && t != '(') return false; if(s[i] == ']' && t != '[') return false; if(s[i] == '}' && t != '{') return false; } } return tmp.empty()?true:false; }};class Solution {public: bool isValid(string s) { stack<char> paren; for (char& c : s) { switch (c) { case '(': case '{': case '[': paren.push(c); break; case ')': if (paren.empty() || paren.top()!='(') return false; else paren.pop(); break; case '}': if (paren.empty() || paren.top()!='{') return false; else paren.pop(); break; case ']': if (paren.empty() || paren.top()!='[') return false; else paren.pop(); break; default: ; // pass } } return paren.empty() ; }};

71. Simplify Path

题目描述

Given an absolute path for a file (Unix-style), simplify it.For example,path = "/home/", => "/home"path = "/a/./b/../../c/", => "/c"click to show corner cases.Corner Cases:Did you consider the case where path = "/../"?In this case, you should return "/".Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".In this case, you should ignore redundant slashes and return "/home/foo".

代码实现

class Solution {public: string simplifyPath(string path) { string res, tmp; vector<string> stk; stringstream ss(path); while(getline(ss,tmp,'/')) { if (tmp == "" || tmp == ".") continue; if (tmp == ".." && !stk.empty()) stk.pop_back(); else if (tmp != "..") stk.push_back(tmp); cout << tmp << endl; } for(auto str : stk) res += "/"+str; return res.empty() ? "/" : res; }};class Solution {public: string simplifyPath(string path) { string result="", token; stringstream ss(path); vector<string> tokens; while(getline(ss, token, '/')){ if(token=="." || token=="") continue; else if(token==".."){ if(tokens.size()) tokens.pop_back(); } else tokens.push_back(token); } if(!tokens.size()) return "/"; for(int i=0; i<tokens.size(); ++i) result += '/' + tokens[i]; return result; }};

在这里需要注意的是我们使用了stringstream和getline的用法来切割字符串。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表