Leetcode58.Length_Of_Last_Word

从后向前寻找,跳过尾部的空格。
也可用STL中,find_last_not_of()与rfind()完成对第一个非空格字符与字符后第一个空格的寻找。
时间复杂度:O(N)
C++代码:

class Solution {
public:
	int lengthOfLastWord(string s) {
		if (s.empty())
			return 0;
		auto it = s.rbegin();
		int count = 0;
		while (*it == ' ' && it != s.rend())
		{
			count++;
			it++;
		}
		if (count == s.length())
			return 0;
		while (it != s.rend() && *it != ' ')
			it++;
		return it - s.rbegin() - count;
	}
};

猜你喜欢

转载自blog.csdn.net/qq_42263831/article/details/82759409