Skip to content

Instantly share code, notes, and snippets.

@vo
Created April 10, 2012 22:14
Show Gist options
  • Save vo/2354989 to your computer and use it in GitHub Desktop.
Save vo/2354989 to your computer and use it in GitHub Desktop.
wordEnds
/*
* A solution for programming problem "wordEnds":
* http://codingbat.com/prob/p147538
*/
public String wordEnds(String str, String word) {
StringBuffer tmp = new StringBuffer();
int ss=0, idx=-1;
while((idx = str.indexOf(word, ss)) >= 0) {
ss = idx + word.length();
if(idx-1 >= 0) tmp.append(str.charAt(idx-1));
if(ss < str.length()) tmp.append(str.charAt(ss));
}
return tmp.toString();
}
/*
* this one is lisa's solution with a small change
*/
public String wordEnds(String str, String word) {
StringBuffer out = new StringBuffer ();
int s_l = str.length(), w_l = word.length();
for (int i = 0; i < s_l-w_l+1; i++) {
if (str.startsWith(word, i)) {
if (i > 0) out.append(str.charAt(i-1));
if (i+w_l < s_l) out.append(str.charAt(i+w_l));
}
}
return out.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment