58. Length of Last Word

這道題,我想到的直接使用函數,trim()與split(' '),估計面試的時候不行,不能讓你太容易,這道題原本也不難,哈哈java

C#版本面試

public class Solution {
    public int LengthOfLastWord(string s) {
        if (s.Length == 0) return 0;
            String[] arr = s.Trim().Split(' ');
            int len = arr.Count();
            return arr[len - 1].Length;
    }
}函數

---------------------------------------------------------------------------------------string

java版本it

class Solution {
    public int lengthOfLastWord(String s) {
        int res = 0,tag = 0;
        for(int i = s.length() - 1; i >=0;i--){
            if(s.charAt(i) == ' ' && tag != 1)continue;
            if(s.charAt(i) != ' '){
                res++;
                tag = 1;
            } else{
                break;
            }
        }
        return res;
    }
}io

res用於返回長度,tag用作標識,標識當前數據是否忽略結尾的空字符,主要代替trim()。ast

加上if(s.length() == 0) return 0;感受更好一些class

相關文章
相關標籤/搜索