Length of Last Word

来源:互联网 发布:淘宝金牌卖家怎么申请 编辑:程序博客网 时间:2024/06/13 23:05

 

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.


#include<iostream>#include<string>using namespace std;int getlen(char*);int main(){char* p = "jb akb lah  nkahg  ";int len = getlen(p);cout << len << endl;system("pause");return 0;}int getlen(char* data){int len = strlen(data);int i = len - 1;int j;while (i >= 0){if (data[i] == ' '){i--;}else{j = i;while (j >= 0){if (data[j] != ' ')j--;elsebreak;}break;}}return i - j;}
class Solution {public:    int lengthOfLastWord(string s) {        int len=s.size();        int i=len-1;        while(i>=0)        {            if(s[i]==' ')            {                i--;            }            else            break;        }        int j=i;        while(j>=0)        {            if(s[j]!=' ')            {                j--;            }            else            break;        }              return i-j;           }};



0 0
原创粉丝点击