1. 题目
2. 解题思路
- 郑重声明,方法一是我自己舍近求远为了找寻一种使用
substring
的方法而特地编写的,所以很麻烦,不建议使用,有兴趣的可以自己看一下代码 - 方法二是一种更加容易想到的方法,这里只讲一下方法二我的思路。
方法二:
-
将这个
string
从后向前遍历,因为要找到是最后一个字符串。 -
在遍历的过程中,如果遇到空格的情况,也就是
' '
的情况,count
不计数,一直从后向前遇到第一个字母开始计数。 -
当再遇到下一个空格的时候就进行输出
count
的值, -
如果到整个序列遍历完也没有遇到下个
' '
那就直接把现有的count
值return
回去
3. 代码
3.1 方法一代码
class Solution {
public static int lengthOfLastWord(String s) {
int fin = 0;
if (s.length()==0) return 0;
int i = s.length()-1;
while(s.charAt(i)== ' '&& i>0){ //这里是防止连续出现空字符
i--;
}
if (s.charAt(i)!=' ') {
fin = i+1;
}
else if (i==0)return 0;
String str =s.substring(0,fin);
s = s.substring(0,fin);
for (int j = 0; j < s.length(); j++) {
if (s.charAt(j)==' '){
str = s.substring(j+1,fin);
}
}
return str.length();
}
}
3.2 方法二代码
class Solution {
public static int lengthOfLastWord(String s) {
int i = s.length()-1;
int count = 0;
for(i=s.length()-1;i>=0;i--){
if (s.charAt(i)!=' ') count ++;
if (count>0 && s.charAt(i)==' '){
return count;
}
}
return count;
}
}