Need a more optimized code.


  • 0
    S

    My solution was accepted by oj,but I am looking for a better solution.So,share yours if yours is better.

    int lengthOfLastWord(const char *s) {
    	int count=0,i=0,flag=0;
    	while(i<strlen(s)){
    		if(s[i]==' ')
    			flag=1;
    		else{
    			if(flag){
    				count=0;
    				flag=0;
    			}
    			count++;
    		
    		}
    			i++;
    	}
    	return count;
    }

  • 3
    P

    Hi, below is my code. It lookes simpler.

    int lengthOfLastWord(const char *s) {
        int length = strlen(s);
        for (length--; length >= 0 && s[length] == ' '; length--) ;
        int res = 0;
        for (int i = length; i >= 0 && s[i] != ' '; i--, res++) ;
        return res;
    }

  • 2
    S

    Here is my Java solution. I used split method in String class. The code is only 2 lines.

    public class Solution {
        public int lengthOfLastWord(String s) {
            String[] tokenStrArray = s.split("\\s+");
            return tokenStrArray.length == 0 ? 0 : tokenStrArray[tokenStrArray.length - 1].length();
        }
    }

  • 0
    V

    using C++ stringstream

    int lengthOfLastWord(const char *s) {
        string str;
        stringstream ss(s);
        while (ss >> str);
        return str.size();
    }

  • 2
    A
    int lengthOfLastWord(const char *s) 
    {
        int t = 0, cur = 0;
        while(*s!='\0')
        {
            if(*s==' ')
            {
                if(cur) t = cur;
                cur = 0;
            }
            else
                cur++;
            s++;
        }
        return cur?cur:t;
    }
    

    almost same code, but better avoid using library functions even strlen


  • 1
    S

    My solution: Scan from the end of string, and then count the number of non-space characters between the first and the second space character.

    int lengthOfLastWord(const char *s) {
        int result = 0;
    
        int len = strlen(s);
    
        for (int i = len - 1; i >= 0; --i) {
            if (s[i] != ' ') {
                ++result;
            } else if (result) {
                break;
            }
        }
    
        return result;
    }

  • 0
    J

    I use python. I was so tempted to use the split method... but like others I just did a backward counting. Runtime 120 ms.

    class Solution:
    # @param s, a string
    # @return an integer
    def lengthOfLastWord(self, s):
        index = len(s) -1
        wordLength = 0
        while index > -1 and wordLength==0:
            if s[index]==" ":
                index -= 1
            else:
                while s[index] != " " and index > -1:
                    wordLength += 1
                    index -= 1
        return wordLength
    

    I used the split method too. Takes 96 ms...


Log in to reply
 

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