国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

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的用法來切割字符串。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 蒙山县| 东港市| 建阳市| 祁门县| 东阳市| 凤翔县| 阳山县| 疏附县| 桐乡市| 阿勒泰市| 咸丰县| 瑞昌市| 介休市| 龙陵县| 衡阳县| 建瓯市| 获嘉县| 长顺县| 乐昌市| 尼木县| 安新县| 泗水县| 松滋市| 德安县| 韶关市| 黑水县| 茂名市| 武陟县| 荔波县| 西乡县| 长春市| 普兰店市| 宁津县| 巴东县| 佛学| 遵化市| 鹰潭市| 南京市| 邢台县| 临沂市| 仪征市|