*************
C++
题目:58. 最后一个单词的长度 - 力扣(LeetCode)
*************
简单的看一下题目:
今天的这个题目比较的简单,感觉比前几天的动态规划要简单点。第一眼看到题目的时候,只知道只要求最后一个的长度,我直接从最后开始数,就能解决。
因此,起手就是一个简单的容器用于存放单词的长度,还有就是我得让计算机知道从最后一个单词开始遍历。
class Solution {
public:
int lengthOfLastWord(string s) {
int length = 0; // to record the length of the last word
int tail = s.length() - 1; // tail start from the end of the string
}
};
怎么判断最后一个单词呢?接下来请出我的老伙计,矩阵,为了便于我理解,矩阵无处不在。
s | h | i | , | y | a |
指针 | 0 | 1 | 2 | 3 | 4 |
指针从4 -> 0遍历,当指针遇到‘ ’,这就代表最后一个单词结束。因此主体函数也可以写出来:
从最后一个字母开始
指针向前移动
如果没有遇到‘,’,那么就记录的长度 +1
指针继续向前移动
遇到‘,’,break
循环结束
class Solution {
public:
int lengthOfLastWord(string s) {
int length = 0; // to record the length of the last word
int tail = s.length() - 1; // tail start from the end of the string
while (tail >= 0 && s[tail] != ' '){
length++;
tail--;
}
return length;
}
};
这段代码写下来,看着很简单,但是,运行不正确,shift。
原因是,字符串的最后还是有空格的。代码运行看到空格,就直接结束了。这个是不对的。因此需要在最开始的时候要跳过空格。
class Solution {
public:
int lengthOfLastWord(string s) {
int length = 0; // to record the length of the last word
int tail = s.length() - 1; // tail start from the end of the string
// skip the space in the last
while (tail >= 0 && s[tail] == ' '){
tail--;
}
// then start to count the length of the last word
while (tail >= 0 && s[tail] != ' '){
length++;
tail--;
}
return length;
}
};
这里有一个新的知识点:
S && M 代表要同时满足 SM;
S || M 代表满足 S 或者 M;
U != SM 代表如果U是SM,条件为真;
U == SM 代表U是SM;
U = SM 代表U现在是SM了。
OK,周四了,明天又是周五了。
有一串很牛逼的代码:
#include wallet
creazy Thu V 50 for KFC