LeetCode 模拟&栈 Simplify Path

来源:互联网 发布:联合国数据 编辑:程序博客网 时间:2024/04/29 14:50

思想:

模拟栈,只保存路径(目录)名字;

对于“.”,跳过;

对于“..”,若不为空,弹栈;

class Solution {public:    string simplifyPath(string path) {        vector<string> stack;        for(auto i=path.begin(); i!=path.end();) {            i++;            auto j = find(i, path.end(), '/');            auto s = string(i, j);            if(!s.empty() && s != ".") {                if(s == "..") {                    if(!stack.empty()) stack.pop_back();                }else {                    stack.push_back(s);                }            }            i = j;        }        stringstream out;        if(stack.empty()) {            out<<"/";        }else {            for(auto s : stack) {                out<<"/"<<s;            }        }        return out.str();    }};


学习了stringstream的使用:#include <sstream>

stringstream继承自iostream;

基本用法:

Objects of this class use a string buffer that contains a sequence of characters. This sequence of characters can be accessed directly as a string object, using member str.

eg:

stringstream out;

string s = out.str();


Characters can be inserted and/or extracted from the stream using any operation allowed on both input and outputstreams.

eg:

out<<"Hello,world";




java:

public class Solution {    public String simplifyPath(String path) {        Deque<String> stack = new LinkedList<String>();        Set<String> skip = new HashSet<String>(Arrays.asList(            "..",            ".",            ""            ));                    for(String dir: path.split("/")) {            if(dir.equals("..") && !stack.isEmpty()) {                stack.pop();            }else if(!skip.contains(dir)) {                stack.push(dir);            }        }                String res = "";        for(String dir: stack) {            res = "/" + dir + res;        }                return res.isEmpty() ? "/" : res;    }}



0 0
原创粉丝点击