Problem 58: Length of Last Word
思路
从后往前慢慢走
public class Solution {
public int lengthOfLastWord(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int len = s.length(), j = len - 1;
while (j >= 0 && s.charAt(j) == ' ') j--;
if (j < 0) {
return 0;
}
int count = 0;
while (j >= 0 && s.charAt(j) != ' ') {
count++;
j--;
}
return count;
}
}
易错点
注意 space 要留出 space
s.charAt(j) == ' '
这里不能写成
s.charAt(j) == ''
否则,charAt没法对应一个位置了。
Last updated
Was this helpful?