Skip to content

Instantly share code, notes, and snippets.

@doyonghoon
Created November 8, 2015 01:33
Show Gist options
  • Save doyonghoon/44026e0d721ae8764ebe to your computer and use it in GitHub Desktop.
Save doyonghoon/44026e0d721ae8764ebe to your computer and use it in GitHub Desktop.
interview problem 1
package com.spencerdo.brain;
/**
* Created by doyonghoon on 2015. 11. 7..
*/
public class MrJohnSmith {
private static final String NAME = "Mr John Smith";
private static final char[] whitespace = new char[]{'0', '2', '%'};
public String getResult() {
char[] s = createTestName(NAME).toCharArray();
int k = 0, p = s.length - 1;
for (int i = s.length - 1; i > 0; i--) {
if (s[i] != ' ') {
k = i;
break;
}
}
while (k >= 0) {
if (s[k] != ' ') {
s[p] = s[k];
p--;
} else {
for (char c : whitespace) {
s[p] = c;
p--;
}
}
k--;
}
return String.valueOf(s);
}
private String createTestName(String s) {
int count = getCharacterCount(s, ' ');
StringBuilder builder = new StringBuilder(s);
for (int i = 0; i < count; i++) {
builder.append(' ').append(' ');
}
return builder.toString();
}
private int getCharacterCount(String s, char target) {
int count = 0;
for (char c : s.toCharArray()) {
if (c == target) {
count++;
}
}
return count;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment