LeetCode58 返回最后一个字符串的最后一个单词的长度

来源:互联网 发布:win8动态壁纸软件 编辑:程序博客网 时间:2024/06/03 16:37

最开始,我的代码在开始输入”a “这种情况下通不过一些用例,知道最后我发现运用s = s.trim()可以解决这个问题,去除字符串开头和结尾的所有的空格。

package genius.wyx.Algorithms;public class WYX58 {    public static int lengthOfLastWord(String s) {        s = s.trim();        if (s.length()==0) {            return 0;        }        int count = 0;        int flag = 0;        for (int i = s.length()-1; i >= 0; i--) {            String c= " ";            if (s.charAt(i) == c.charAt(0)) {                flag = 1;                return count;            }            count++;        }        if (flag==0) {            return s.length();        }        return 0;    }    public static void main(String[] args) {        String string = "a    b    cd   ";        System.out.println(lengthOfLastWord(string));    }}
原创粉丝点击