Created
April 10, 2012 22:14
-
-
Save vo/2354989 to your computer and use it in GitHub Desktop.
wordEnds
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
/* | |
* 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 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
/* | |
* 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