Created
May 23, 2017 19:18
-
-
Save BiruLyu/f71c1dcee869f3d0dedc29cb8a96bda4 to your computer and use it in GitHub Desktop.
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 class Solution { | |
| public int lengthOfLastWord(String s) { | |
| int res = 0; | |
| s = s.trim(); | |
| if(s == "") return res; | |
| for(int i = s.length() - 1; i >= 0; i--){ | |
| if(s.charAt(i) == ' '){ | |
| res = s.length() - i - 1; | |
| break; | |
| } | |
| } | |
| return res == 0 ? s.length() : res; | |
| } | |
| } | |
| /* | |
| Input: | |
| "" | |
| "Hello World " | |
| "World" | |
| "World " | |
| "b a " | |
| Output: | |
| 0 | |
| 5 | |
| 5 | |
| 5 | |
| 1 | |
| */ |
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
| class Solution(object): | |
| def lengthOfLastWord(self, s): | |
| """ | |
| :type s: str | |
| :rtype: int | |
| """ | |
| lengthLast = 0; | |
| for i in range(len(s)-1,-1,-1): | |
| if s[i] == ' ' and lengthLast == 0: | |
| continue; | |
| if s[i] == ' ': | |
| break; | |
| lengthLast += 1; | |
| return lengthLast; | |
| """ | |
| TESTCASES: | |
| Input: | |
| "" | |
| "Hello World" | |
| "Hello" | |
| "Hello World we" | |
| "a " | |
| "a aa " | |
| "a aaa " | |
| Output: | |
| 0 | |
| 5 | |
| 5 | |
| 2 | |
| 1 | |
| 2 | |
| 3 | |
| """ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment