leetcode [Length of Last Word]

    xiaoxiao2021-03-25  49

    public class Solution { public int lengthOfLastWord(String s) {//题目要求的是求字符串中最后一个单词的长度 int res = 0, i = 0; if(s.length() == 0) return 0;//空串先处理 int count = s.length() - 1; //确定从最后开始第一个不为空格的地方 for(;count >= 0; count--){//不用while循环,防止下标越界 if(s.charAt(count) != ' ') break; } for(i = count; i >= 0; i--){//字符串中有多个单词 if(s.charAt(i) == ' ') return count - i; } if(i == -1 && count == s.length() - 1) return s.length();//字符串中只有一个单词 if(i == -1 && count != s.length() - 1) return count + 1;//字符串中空格从末尾开始 return res; } }

    注意代码整洁(解法一样,修改了细节)

    class Solution { //注意代码的整洁(对比上面的代码) public int lengthOfLastWord(String s) {//题目要求的是求字符串中最后一个单词的长度 int res = 0, i = 0; int count = s.length() - 1; //确定从最后开始第一个不为空格的地方 for(;count >= 0 && s.charAt(count) == ' '; count--);//不用while循环,防止下标越界 for(i = count; i >= 0 && s.charAt(i) != ' '; i--) res++;//既然有res,用一个计数的,不用去算返回count - i啥的作为长度 return res; } }

    转载请注明原文地址: https://ju.6miu.com/read-26027.html

    最新回复(0)