C++ solution hanldes the case when string.length() > INT_MAX


  • 0
    M

    The question didn't limit the length of input string lower than INT_MAX (We should ask the interviewer). Thus I wrote below code to handle the case when string.length() > INT_MAX:

    class Solution {
    public:
        int lengthOfLastWord(string s) {
            if (s.empty())
            {
                return 0;
            }
            
            int l = 0;
            size_t i = s.size() - 1;
            while (i > 0 && s[i] == ' ')
            {
                --i;
            }
            
            if (i == 0 && s[i] == ' ')
            {
                return 0;
            }
            
            while(i > 0 && s[i] != ' ')
            {
                ++l;
                --i;
            }
            
            if (i == 0 && s[i] != ' ')
            {
                ++l;
            }
            
            return l;
        }
    };
    

Log in to reply
 

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