Skip to content

Instantly share code, notes, and snippets.

@jraczak
Created February 23, 2017 00:48
Show Gist options
  • Save jraczak/5e3620a00d5c1ef726192ff8af3feaa3 to your computer and use it in GitHub Desktop.
Save jraczak/5e3620a00d5c1ef726192ff8af3feaa3 to your computer and use it in GitHub Desktop.
problem 2
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;
}
@phillippattisc
Copy link

phillippattisc commented Feb 23, 2017

String newString = "";

name of this variable is ambiguous.
sWithoutDashes
sNoDashes
sDashesRemoved

@phillippattisc
Copy link

phillippattisc commented Feb 23, 2017

String[] stringParts = s.split("-"); String newString = ""; String reformattedString = ""; int startLocation = 0; for (String stringPart : stringParts) { newString = newString + stringPart; }

Most languages have a s.replace("-", "") or similar, just an fyi

if not / if they want you to code it, best to pull this out into another function

@phillippattisc
Copy link

if (reformattedString.startsWith("-")) {

This would mean that k was 0, catch this at the beginning

@phillippattisc
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment