Find length of last word: Java Solution


  • 0
    P
    class Solution {
        public int lengthOfLastWord(String s) {
            int back = 0;
            int front = 0;
            String space = " ";
            String dups = s.trim();
            boolean haveSpace = false;
            System.out.println(s.length());
            for (int i =0;i<dups.length();i++){
               front=i;           
                if (dups.charAt(i)==space.charAt(0)){
                    System.out.println("hellofrominside");
                    haveSpace = true;
                    back=front;                                
                }
                if ((i==dups.length()-1)&&(haveSpace)){
                    
                    return front-back;
                }
            }
            if (haveSpace==false){
                return dups.length();
            }
            return front-back;
        }
    }

Log in to reply
 

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