详细见:leetcode.com/problems/length-of-last-word
Java Solution: github
package leetcode;
public class P058_LengthOfLastWord {
public static void main(String[] args) {
System.out.println(new Solution().lengthOfLastWord(" "));
}
/*
* 1 ms
* 43.86%
*/
static class Solution {
public int lengthOfLastWord(String s) {
int len = 0;
if (s == null || (len = s.length()) == 0)
return 0;
boolean start = false;
for (int i = len - 1; i != -1; i --) {
char c = s.charAt(i);
if (c != ' ') {
if (! start) {
len = i;
start = true;
}
} else {
if (start)
return len - i;
}
}
return start ? len + 1 : 0;
}
}
}
C Solution: github
/*
url: leetcode.com/problems/length-of-last-word/
AC 3ms 7.44%
*/
int lengthOfLastWord(char* s) {
int ans = 0, i = 0;
char c = '\0';
while (1) {
if (s[i] == '\0') break;
if (s[i] != ' ') {
if (c == ' ') ans = 1;
else ans ++;
}
c = s[i++];
}
return ans;
}
int main() {
char* s = "w World ";
printf("answer is %d\r\n", lengthOfLastWord(s));
}
Python Solution: github
#coding=utf-8
'''
url: leetcode.com/problems/length-of-last-word
@author: zxwtry
@email: zxwtry@qq.com
@date: 2017年4月12日
@details: Solution: 39ms 80.79%
'''
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
if s == None: return 0
ans, index = 0, len(s)-1
while index > -1:
if s[index] == " ":
if ans != 0: break
index -= 1
continue
ans += 1
index -= 1
return ans
if __name__ == "__main__":
print(Solution().lengthOfLastWord(" ab "))


被折叠的 条评论
为什么被折叠?



