Java Without Trim Or Library O(n)


  • 0
    I

    I saw best solution as using trim or n square solutions.I tried without using any library.

    If current space char is followed by another space char - it is ignored
    if current space char is last character of the string - it is ignored

    if current space char is NOT followed by another space char - reset the count to 0

    public int lengthOfLastWord(String s) {
            int count = 0;
    
            for (int i = 0 ; i < s.length(); i++){
                char currentChar = s.charAt(i);
    
                if((currentChar == ' ' && i < s.length() - 1 && s.charAt(i + 1) == ' ') || (currentChar == ' ' &&
                        i == s.length() - 1)){
                    continue;
                }
                else if(currentChar == ' ' && i<s.length() - 1 && s.charAt(i+1) != ' '){
                    count = 0;
                }
                else {
                    count++;
                }
            }
    
            return count;
        }

Log in to reply
 

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