从Simplify Path问面试编程语言选择?# JobHunting - 待字闺中
a*e
1 楼
leetcode上的,感觉如果选择的语言有split这个function,就会好写很多,比如C#和
Java。
C++就麻烦些。而且选择是algorithm 的find还是string的find也很不同。
面试时碰到这类题能说我这道题用C#或者Java,其他用C++行么?其实现在主要用C#,
但C++是总共用得最久的。Java感觉和C#很像,但实际工作中没用过,也不想为面试而
学。多谢
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
两个C++的
1. string simplifyPath(string path) {
vector a;
int n = path.size();
for (int i = 0; i {
string t;
size_t j = path.find('/', i); //用string的 find
if (j != string::npos)
t = path.substr(i, j - i);
else
{
t = path.substr(i, n - i);
}
if (t == "." || t == "")
{
if (j != string::npos)
{
i = j + 1;
continue;
}
else
break;
}
if (t == "..")
{
if (!a.empty())
a.pop_back();
else
{
if (j != string::npos)
{
i = j + 1;
continue;
}
else
break;
}
}
else
{
a.push_back(t);
t.clear();
}
if (j != string::npos)
i = j + 1;
else
break;
}
int m = a.size();
string ret;
if (m == 0)
ret = "/";
else
{
for (int i = 0; i {
ret += "/";
ret += a[i];
}
}
return ret;
}
2. string simplifyPath(string path) {
vector a;
for (auto i = path.begin(); i != path.end();) {
++i;
auto j = find(i, path.end(), '/');
auto dir = string(i, j);
if (!dir.empty() && dir != ".") {//
if (dir == "..") {
if (!a.empty())
a.pop_back();
} else
a.push_back(dir);
}
i = j;
}
int m = a.size();
string ret;
if (m == 0)
ret = "/";
else
{
for (int i = 0; i {
ret += "/";
ret += a[i];
}
}
return ret;
}
Java。
C++就麻烦些。而且选择是algorithm 的find还是string的find也很不同。
面试时碰到这类题能说我这道题用C#或者Java,其他用C++行么?其实现在主要用C#,
但C++是总共用得最久的。Java感觉和C#很像,但实际工作中没用过,也不想为面试而
学。多谢
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
两个C++的
1. string simplifyPath(string path) {
vector
int n = path.size();
for (int i = 0; i
string t;
size_t j = path.find('/', i); //用string的 find
if (j != string::npos)
t = path.substr(i, j - i);
else
{
t = path.substr(i, n - i);
}
if (t == "." || t == "")
{
if (j != string::npos)
{
i = j + 1;
continue;
}
else
break;
}
if (t == "..")
{
if (!a.empty())
a.pop_back();
else
{
if (j != string::npos)
{
i = j + 1;
continue;
}
else
break;
}
}
else
{
a.push_back(t);
t.clear();
}
if (j != string::npos)
i = j + 1;
else
break;
}
int m = a.size();
string ret;
if (m == 0)
ret = "/";
else
{
for (int i = 0; i
ret += "/";
ret += a[i];
}
}
return ret;
}
2. string simplifyPath(string path) {
vector
for (auto i = path.begin(); i != path.end();) {
++i;
auto j = find(i, path.end(), '/');
auto dir = string(i, j);
if (!dir.empty() && dir != ".") {//
if (dir == "..") {
if (!a.empty())
a.pop_back();
} else
a.push_back(dir);
}
i = j;
}
int m = a.size();
string ret;
if (m == 0)
ret = "/";
else
{
for (int i = 0; i
ret += "/";
ret += a[i];
}
}
return ret;
}