Why am I getting wrong answer? Java


  • 0
    L

    I cannot understand this. Same code in C++ is accepted but in Java, it turns out

    Input:	"a"
    Output:	0
    Expected:	1
    

    Anyone could help? Thank you!

    public class Solution {
        public int lengthOfLastWord(String s) {
         int sum = 0;
         int length = s.length() -1 ;
         
         while(length>0 && (s.charAt(length))==' '){
             length--;
         }
         
         while(length>0 && s.charAt(length)!=' '){
             sum++;
             length--;
         }
         return sum;
            
        }
    }

  • 0
    H

    should be while(length>=0)


Log in to reply
 

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