Easy understanding Java solution


  • 0
    Z

    Traverse twice from the end the string. First find the last word position, then start from the last word position and find the last space position. Set the default the space position as -1.
    O(n) time

    public class Solution {
        public int lengthOfLastWord(String s) {
    		// find last word position
    		int word = -1;
    		for(int i=s.length()-1; i>=0; i--){
    			if(s.charAt(i) != ' ') {word = i; break;}
     		}
     		// if last word does not exist
     		if(word==-1) return 0;
     		// find the last space position
     		int space = -1;
     		for(int i=word; i>=0; i--){
     			if(s.charAt(i) == ' ') {space = i; break;}
      		}
      		return word - space;
        }
    }
    

Log in to reply
 

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