题解 | #牛群的危险路径#
牛群的危险路径
https://www.nowcoder.com/practice/c3326fb3ac0c4a658305483482943074
题目考察的知识点:字符串的遍历
题目解答方法的文字分析:先将相邻的"//"删掉一个;然后入栈,遇到"."出栈;然后栈中的元素就是最简路径,入string中,翻转字符串。
本题解析所用的编程语言:c++
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param path string字符串
* @return string字符串
*/
string find_dangerous_cow_path(string path)
{
// write code here
//将相邻的"//"删掉一个
auto it = path.begin();
while (it != path.end() - 1)
{
if ((*it) == '/' && *(it + 1) == '/')
path.erase(it + 1);
++it;
}
//入栈
stack<char> ret;
for (int i = 0; i < path.size(); ++i)
{
if (path[i] == '.')
{
while (!ret.empty() && ret.top() != '/')
{
ret.pop();
}
if (!ret.empty())
ret.pop();
}
else
ret.push(path[i]);
}
//入string
string rpath;
while (!ret.empty())
{
rpath += ret.top();
ret.pop();
}
//翻转
reverse(rpath.begin(), rpath.end());
if (rpath.size() > 1 && rpath[rpath.size() - 1] == '/')
rpath.erase(rpath.end() - 1);
return rpath;
}
};
