Skip to content

Instantly share code, notes, and snippets.

@cangoal
Last active March 20, 2016 04:35
Show Gist options
  • Save cangoal/1ed9c51764a234b744cb to your computer and use it in GitHub Desktop.
Save cangoal/1ed9c51764a234b744cb to your computer and use it in GitHub Desktop.
LeetCode - Length of Last Word
//
public int lengthOfLastWord(String s) {
if(s==null || s.length()==0) return 0;
int i=s.length()-1;
for(; i>=0; i--){
if(s.charAt(i) != ' ') break;
}
int j = i;
for(; j>=0; j--){
if(s.charAt(j) == ' ') break;
}
return i - j;
}
//
public int lengthOfLastWord(String s) {
if(s==null || s.length()==0) return 0;
int idx = s.length()-1;
while(idx>=0 && s.charAt(idx)==' ') idx--;
int idx2 = idx;
while(idx2>=0 && s.charAt(idx2)!=' ') idx2--;
return idx-idx2;
}
//
public int lengthOfLastWord(String s) {
if(s==null || s.length()==0) return 0;
String[] strs = s.split(" ");
if(strs.length==0) return 0;
return strs[strs.length-1].length();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment