58. Length of Last Word

题目

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.

Example:

Input: "Hello World"
Output: 5

解析

  • 主要处理末尾的空格!!
class Solution_58 {
public:

	// 反向查找,末尾空格忽略,行中出现空格就终止循环

	int lengthOfLastWord(string s) {
		int ret = 0;
		if (s.empty())
		{
			return ret;
		}
		int i = s.size() - 1;
		while (i>=0&&s[i] == ' ')
		{
			i--;
		}
			
		for (; i >= 0;i--)
		{	
			if (s[i]==' ')
			{
				break;
			}
			ret++;
		}
		return ret;
	}

	int lengthOfLastWord(const char *s) {

		int ret = 0;
		int len = strlen(s);

		for (int i = len - 1; i >= 0;i--)
		{
			if (s[i]==' ')
			{
				if (ret) //忽略末尾的空格,当遇到空格且有元素时,返回
				{
					break;
				}
			}
			else
			{
				ret++;
			}
		}
		return ret;
	}
};

题目来源

C/C++基本语法学习 STL C++ primer