path
的最後一個字元為 '\'
的這個特殊狀況。path
的最後一個字元為 '\'
時,第 17 行的 while
迴圈條件不成立,而停止對 name
的操作。在執行完第 22 ~ 33 行的程式後,第 7 行的最外層 while
迴圈的條件仍然成立 (因為此時 i
的值為path.size() - 1
)。所以仍會進入第 8 ~ 10 行的 while
迴圈,使得 i
的值更新為 path.size()
。那麼緊接著第 8 行的 while
迴圈條件失敗後,第 11 行的 if
條件成立,並執行第 13 行的 break
,然後離開第 7 ~ 34 行的整個 while
迴圈。
class Solution {
public:
string simplifyPath(string path) {
int i = 0;
stack<string> st;
while (i < path.size()) {
while (i < path.size() && path[i] == '/') {
++i;
}
if (i >= path.size()) {
// We have can the whole path.
break;
}
string name;
while (i < path.size() && path[i] != '/') {
name.push_back(path[i]);
++i;
}
if (name == ".") {
continue;
}
if (name == "..") {
if (!st.empty()) {
st.pop();
}
continue;
}
st.push(name);
}
if (st.empty()) {
return "/";
}
string answer;
while (!st.empty()) {
answer = "/" + st.top() + answer;
st.pop();
}
return answer;
}
};
class Solution {
public:
string simplifyPath(string path) {
stack<string> st;
for (int i = 1; i < path.size(); ++i) {
string file;
while (path[i] != '/' && i < path.size()) {
file += path[i];
++i;
}
processStack(file, st);
} // end of for-loop
string answer;
while (!st.empty()) {
answer = st.top() + answer;
st.pop();
}
if (answer.size() == 0) {
answer = "/";
}
return answer;
}
void processStack(string& file, stack<string>& st) {
if (file.size() == 0 || file == ".") {
return;
}
if (file == "..") {
if (!st.empty()) {
st.pop();
}
return;
}
st.push("/" + file);
}
};
\(O(n)\)
\(n\) is the length of path
.
\(O(H + n)\)
\(n\) is the length of path
.
\(H\) is the depth of the filesystem.
or
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up
Syntax | Example | Reference | |
---|---|---|---|
# Header | Header | 基本排版 | |
- Unordered List |
|
||
1. Ordered List |
|
||
- [ ] Todo List |
|
||
> Blockquote | Blockquote |
||
**Bold font** | Bold font | ||
*Italics font* | Italics font | ||
~~Strikethrough~~ | |||
19^th^ | 19th | ||
H~2~O | H2O | ||
++Inserted text++ | Inserted text | ||
==Marked text== | Marked text | ||
[link text](https:// "title") | Link | ||
 | Image | ||
`Code` | Code |
在筆記中貼入程式碼 | |
```javascript var i = 0; ``` |
|
||
:smile: | ![]() |
Emoji list | |
{%youtube youtube_id %} | Externals | ||
$L^aT_eX$ | LaTeX | ||
:::info This is a alert area. ::: |
This is a alert area. |
On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?
Please give us some advice and help us improve HackMD.
Do you want to remove this version name and description?
Syncing