Another simple solution


  • 5
    G
         int lengthOfLastWord(const char *s) {
            int len  = strlen(s);
            int i=len-1;
    
            while(s[i]==' ')   //remove the spaces from end
             i--;
          
            int j; 
            for( j= i; j>=0; j--)   //u got a word
            {
               if(s[j]==' ')       /break before hitting second last word
                 break;
            }
            return i-j;     //return length
    }

  • 5
    S

    My code is in java

    public int lengthOfLastWord(String s) {
            if ( s.length() == 0)  return 0;  
          
            int len = s.length();  
            int count = 0;  
    
            for (int i = len - 1; i >=0; i--) {  
                if (s.charAt(i) != ' ')  count++;  
                  
                if(s.charAt(i)==' '&&count != 0)  return count;   
            }  
            return count;  
        }
    

  • 0
    G
    public class Solution {
        public int lengthOfLastWord(String s) {
            if (s == null || s.isEmpty()) return 0;
            
            int l = 0;
            int lastCharPos = s.length() - 1;
            
            while ( lastCharPos >= 0 && s.charAt(lastCharPos) == ' ') 
                lastCharPos--;
    
            for (int i = lastCharPos; i >= 0 && s.charAt(i) != ' '; i--) 
                l++;
            
            return l;
        }
    }

  • 0
    B

    it is wrong if input is " ".
    i will be negative and your while will become run time error


Log in to reply
 

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