1 static int wing=[]() 2 { 3 std::ios::sync_with_stdio(false); 4 cin.tie(NULL); 5 return 0; 6 }(); 7 8 class Solution 9 { 10 public: 11 int lengthOfLastWord(string s) 12 { 13 int len=s.length(); 14 if(len==0) 15 return 0; 16 int i=len-1; 17 while(!isalpha(s[i])) 18 --i; 19 if(i<0) 20 return 0; 21 int count=0; 22 while(i>=0) 23 { 24 if(!isalpha(s[i])) 25 break; 26 ++count; 27 --i; 28 } 29 return count; 30 } 31 };
Scan from back to forward until the first letter, start counting, encounter a non-letter or reach the beginning of the string, stop counting, and output the result.