58. Length of Last Word

    xiaoxiao2021-03-25  111

    Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

    If the last word does not exist, return 0.

    Note: A word is defined as a character sequence consists of non-space characters only.

    For example,  Given s = "Hello World",

    return 5.

    问题:返回最后一个单词的长度,注意情况“abc hello   ”末尾有空格情况

    public int lengthOfLastWord(String s) { if(s==null||s.length()<1) return 0; int len=0; int j=s.length()-1; for(;j>=0;j--){ if(s.charAt(j)!=' ') break; } for(int i=j;i>=0;i--){ if(s.charAt(i)==' ') break; len++; } return len; }

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

    最新回复(0)