58. Length of Last Word

来源:互联网 发布:逆袭网络剧百度云网盘 编辑:程序博客网 时间:2024/05/29 16:30


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.

第一种方法:因为之前写了一个reverse函数,就想着用现成的,这个真的太繁琐,晕!

public void reverse(char[] a, int start,int end)    {    if(a==null||start<0||end>a.length-1)    return;    while(start<=end)    {    char b=a[start];    a[start]=a[end];    a[end]=b;    start++;    end--;    }    }public int lengthOfLastWord(String s) {                if(s.length()==0||s==null)                return 0;            char[] c=s.toCharArray();            int res=0;            int len=c.length;            int cnt=0;            for(int i=len-1;i>=0;i--)            {            if(c[i]==' ')            cnt++;            else            break;            }            if(cnt>0)            reverse(c,0,len-1-cnt);            else            reverse(c,0,len-1);            for(int i=0;i<len;i++)            {            if(c[i]!=' ')            {            res++;            }            else            break;            }            return res;    }

第二种方法:用split。两行

 public int lengthOfLastWord1(String s)        {        String[] ss=s.split(" ");        return ss.length==0?0:ss[ss.length-1].length();                }

第三种方法:从后往前res++

public static int lengthOfLastWord2(String s)        {        int res=0;        int i=s.length()-1;        while(i>=0&&s.charAt(i)==' ')        {        i--;        }        while(i>=0&&s.charAt(i)!=' ')        {        res++;        i--;        }        return res;        }




0 0
原创粉丝点击