![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/98a1ccb4867c7b10e87147acef7c52bb.png)
暴力搜索
c++:
class Solution {
public:
int lengthOfLastWord(string s) {
int count = 0;
for(int i=s.size()-1; i>=0; i--){
if(s[i]!=' '){
count++;
}else if(s[i]==' ' && count !=0 ){
break;
}
}
return count;
}
};
python
class Solution:
def lengthOfLastWord(self, s: str) -> int:
count = 0
for i in range(len(s)-1,-1,-1):
if s[i]!=' ':
count +=1
elif s[i]==' ' and count != 0:
break
return count
使用函数:
c++ :istringstream 函数
class Solution {
public:
int lengthOfLastWord(string s)
{
istringstream in(s);
string res;
while(in>>res);
return res.size();
}
};
python: strip 函数
class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(s.strip().split(' ')[-1])