Last active
March 20, 2016 04:35
-
-
Save cangoal/1ed9c51764a234b744cb to your computer and use it in GitHub Desktop.
LeetCode - Length of Last Word
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
| // | |
| 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