Last active
January 22, 2019 02:52
-
-
Save yangmillstheory/09745d8760bf00db543343f66edc1777 to your computer and use it in GitHub Desktop.
Compact string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cstring> | |
// Compactify a string in linear time. | |
// | |
// Examples: | |
// | |
// $ compact /foo/bar/baz # /f/b/baz | |
// $ compact foo/bar/baz # f/b/baz | |
// $ compact baz # baz | |
int main(int argc, char const* argv[]) { | |
if (argc < 2) { | |
return 0; | |
} | |
const char* path = argv[1]; | |
char delim = argc == 3 ? argv[2][0] : '/'; | |
int n = std::strlen(path); | |
int m = n; | |
while (m - 1 >= 0 && path[m - 1] != delim) { | |
m--; | |
} | |
char last; | |
for (size_t i = 0; i < m; i++) { | |
char ch = path[i]; | |
if (i == 0 || last == delim || ch == delim) { | |
std::cout << ch; | |
} | |
last = ch; | |
} | |
for (size_t i = m; i < n; i++) { | |
std::cout << path[i]; | |
} | |
std::cout.flush(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment