1. 概述
以 Unix 风格给出一个文件的绝对路径,将其转换为规范路径。
输入:”/a/./b/../../c/“ 输出:”/c”
2. 解题
<?phpclass Solution {/*** @param String $path* @return String*/public function simplifyPath($path) {$elements = explode('/', $path);if (!$elements) {return '';}$stack = new SplStack();foreach ($elements as $v) {if (!$v || $v == '.') {continue;}if ($v == '..') {if ($stack->isEmpty()) {return '';}$stack->pop();} else {$stack->push($v);}}$ret = '';while (!$stack->isEmpty()) {$ret = '/' . $stack->pop();}return $ret ?: '/';}}$path = "/a/./b/../../c/";$cls = new Solution();$r = $cls->simplifyPath($path);echo $r;
