5ms without trim()


  • 0
    A
    public class Solution {
        public int lengthOfLastWord(String s) {
            boolean flag = false;
            int block = 0;
            for(int i=s.length()-1; i>=0; i--){
                if(s.charAt(i)==' ' && !flag) block++;
                if(s.charAt(i)==' ' && flag) return s.length()-1-i-block;
                if(s.charAt(i)!=' ' && !flag) flag=true;
            }
            if(flag)return s.length()-block;
            else return 0;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.