Length of Last Word

来源:互联网 发布:ubuntu 路径 编辑:程序博客网 时间:2024/06/05 21:06

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.


题目解析:

(1)思路还是很清晰的,用一个长度记录每个当前word的长度,当指针向后的时候不断被后来的word的长度所更新

因此到最后得到的长度是最后一个单词的长度


#include <iostream>using namespace std;int lengthOfLastWord(const char *s) {int index = 0;int wordLength = 0;while(s[index]!='\0'){while(s[index]!='\0' && s[index] == ' '){index++;}if (s[index] == '\0'){return wordLength;}else{if( (s[index] >= 'a' && s[index] <= 'z')|| (s[index] >= 'A' && s[index] <= 'Z') ){wordLength = 0;}while( (s[index] >= 'a' && s[index] <= 'z')|| (s[index] >= 'A' && s[index] <= 'Z') ){wordLength++;index++;}}}return wordLength;}int main(void){const char *s = "hello world";int len = lengthOfLastWord(s);cout << len << endl;system("pause");return 0;}


0 0
原创粉丝点击