https://leetcode-cn.com/problems/length-of-last-word/submissions/
本题比较简单,只需从字符串的最后一个字符向前遍历即可,但是需要注意空格,不管末尾有多少个空格,从后向前遍历的时候从第一个非空格的字符开始计数,直到再次遇见空格,退出循环。
class Solution { public int lengthOfLastWord(String s) { if(s.length()==0) return 0; int sum=0,f=0; //sum用来记录最后一个单词长度,f用来区分是最后一个字符前的空格还是之后的空格 for(int i=s.length()-1;i>=0;i--){ if(s.charAt(i)==‘ ‘&&f==1) break; if(s.charAt(i)!=‘ ‘){ sum++; f=1; } } return sum; } }
原文:https://www.cnblogs.com/y1040511302/p/11295796.html