Only count the necessary part (java)


  • 0
    W
    public class Solution {
        public int lengthOfLastWord(String s) {
            int len = s.length();
            int counter = 0;
            boolean flag = false; //check if the counter goes though a word
            for(int i=len-1; i>=0; i--){
            	if(s.charAt(i) != ' '){
            		counter++;
            		flag = true; //found some word to count
            	}
            	if(flag == true && s.charAt(i) == ' ')
            		return counter;
            }
            return counter;
        }
    }

Log in to reply
 

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