1. Manual Character-by-Character State Machine
Intuition
Manually iterate through the string with an index pointer, extract directory names between slashes, and push/pop from a stack.
Algorithm
- Step 1: Initialize an empty stack
stand indexi = 0. - Step 2: Loop while
i < path.length. - Step 3: Skip all consecutive slashes
'/'. - Step 4: Extract token until next slash.
- Step 5: Apply folder/parent/current directory rules.
- Step 6: Join result.
#include <iostream>#include <string>#include <vector> class Solution {public: std::string simplifyPath(std::string path) { std::vector<std::string> st; int n = path.length(); int i = 0; while (i < n) { while (i < n && path[i] == '/') i++; if (i >= n) break; int start = i; while (i < n && path[i] != '/') i++; std::string dir = path.substr(start, i - start); if (dir == ".") continue; if (dir == "..") { if (!st.empty()) st.pop_back(); } else { st.push_back(dir); } } std::string res = ""; for (const std::string& s : st) { res += "/" + s; } return res.empty() ? "/" : res; }}; int main() { Solution solver; std::cout << "Canonical: " << solver.simplifyPath("/home//foo/") << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N)— Single pass over characters extracting tokens without high-level split helpers. - Space complexity:
O(N)— O(N) space for directory stack.
Why Brute Force Doesn't Scale:
Unneeded copies slow down execution on large path inputs.
Directory stack normalizes 10,000 characters in <2ms.