280 ms Java Solution


  • 0
    B

    public class Solution {
    public int lengthOfLastWord(String s) {
    int counter = 0;
    int index = 0;
    String ss = s.trim();

        for(int i=0;i<ss.length();i++){
            if(ss.charAt(i)==' '){
                counter++;
                index=i;
            }
        }
      
        if(ss.length()==1){
       
            return 1;
            
        }else if(ss.length()>1 && counter==0){
        
          return ss.substring(index,ss.length()).length();
          
        }else if(ss.length()>1 && counter>0){
        
          return ss.substring(index+1,ss.length()).length();
            
            
        }else{
            return 0;
        }
        
    }
    

    }


Log in to reply
 

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