解题思路
思路一:
把字符串以空格分开,然后计算出最近一串字母的长度
思路二:
从后向前遍历直到遍历到头或者遇到空格为止
代码
方法一:分割字符串
//运行时间:4ms , 内存消耗:37.2MB
class Solution {
public static int lengthOfLastWord(String s) {
String str = s.trim();
if(str.length() == 0 ) return 0;
String[] strs = str.split("\\s+");// \s:匹配任何空白字符,包括空格、制表符、换页符等 +:一次或多次匹配前面的字符或子表达式
String last_str = strs[strs.length-1];
return last_str.length();
}
}
方法二:从后往前遍历
//运行时间:0ms , 内存消耗:36.5MB
class Solution {
public static int lengthOfLastWord(String s) {
String str = s.trim();
int count=0;
for(int end = str.length()-1 ; end>=0 && str.charAt(end)!=' ' ;end--) {
count++;
}
return count;
}
}