C++ using Squeeze method


  • 0
    class Solution {
    public:
    	int lengthOfLastWord(string s) {
    		int ans = 0;
    		int n = s.size();
    
    		if(n != 0)
    		{
    			int left = -1;
    			int right = n;
    			for(int i = n - 1; i >= 0; --i)
    			{
    				char ch = s[i];
    				if(ch != ' ')
    				{
    					// the first not empty char
    					right = i + 1;
    					break;
    				}
    			}
    			for(int i = 0; i < right; ++i)
    			{
    				char ch = s[i];
    				if(ch == ' ')
    					left = i;
    			}
    
    			ans = right - left - 1;
    		}
    		else
    		{
    			ans = 0;
    		}
    		return ans;
    	}
    };
    

Log in to reply
 

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