Java solution with check for different types of space


  • 0
    P

    It's not the best decision, but I was afraid of different type of spaces like wide space or thin space etc.
    so I used Character.isWhitespace(char ch);

    class Solution {
        public int lengthOfLastWord(String s) {
            if(s == null || s.length() == 0) return 0;
            int result = 0;
            
            int space = 0;
            
            while(Character.isWhitespace(s.charAt(s.length()-1)) 
                    && s.length() > 0) {
                  s = s.substring(0, s.length()-1);
                  if(s.length() < 2) break;
                }  
            
            for(int i = s.length()-1; i >= 0; i--) {          
                if(Character.isWhitespace(s.charAt(i))) { 
                    space = i+1;  
                    break;
                }    
            }
              
        result = s.length() - space;
        if(result < 1) return 0;
            
        return result;
        }           
    }
    

Log in to reply
 

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