标签:style blog http io ar color os sp for
Given a string s consists of upper/lower-case alphabets and empty space characters ‘ ‘
, return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
For example,
Given s = "Hello World"
,
return 5
.
String
1 #include <iostream> 2 #include <cstring> 3 using namespace std; 4 5 6 class Solution { 7 public: 8 int lengthOfLastWord(const char *s) { 9 int n = strlen(s); 10 if(n <1) return 0; 11 int idx=n-1; 12 while(idx>=0&&s[idx]==‘ ‘) idx--; 13 n = idx+1; 14 while(idx>=0){ 15 if (s[idx]==‘ ‘) break; 16 idx --; 17 } 18 // if(idx<0) return 0; 19 return n - idx -1; 20 } 21 }; 22 23 int main() 24 { 25 char s[] = " 12 "; 26 Solution sol; 27 cout<<sol.lengthOfLastWord(s)<<endl; 28 return 0; 29 }
[LeetCode] Length of Last Word 字符串查找
标签:style blog http io ar color os sp for
原文地址:http://www.cnblogs.com/Azhu/p/4141846.html