Created
February 23, 2017 00:48
-
-
Save jraczak/5e3620a00d5c1ef726192ff8af3feaa3 to your computer and use it in GitHub Desktop.
problem 2
This file contains hidden or 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
String stringReformatting(String s, int k) { | |
String[] stringParts = s.split("-"); | |
String newString = ""; | |
String reformattedString = ""; | |
int startLocation = 0; | |
for (String stringPart : stringParts) { | |
newString = newString + stringPart; | |
} | |
int firstSegmentSize = newString.length() % k; | |
reformattedString = newString.substring(0, firstSegmentSize); | |
startLocation += firstSegmentSize; | |
for (int i = startLocation; i < newString.length(); i+=k) { | |
reformattedString = reformattedString + "-" + | |
newString.substring(i, i+k); | |
} | |
if (reformattedString.startsWith("-")) { | |
reformattedString = reformattedString.substring(1); | |
} | |
return reformattedString; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
algorithm looks like it works.
This does it in O(2n), potentially 2 full passes over the string (1 to remove hyphens, 1 to rebuild). I can think of a way it can be done in O(n), 1 pass over the string.