Why My c++ code sometime is right and sometime is "runtime error" for same case?


  • 0

    here is my code :

    class Solution {
    public:
    int expand(int left, int right, const string & s)
    {
    	--left;
    	++right;
    	while (left >= 0 && right<s.size())
    	{
    		if (s[left] != s[right]) break;
    		--left;
    		++right;
    	}
    	return right - left - 1;
    }
    string longestPalindrome(string s) 
    {
    	int all[256];
    	memset(all, -1, 256);
    	int max = 0;
    	int left = 0;
    	for (int i = 0; i < s.size(); ++i)
    	{
    		if (all[s[i]]!=-1 && i - all[s[i]] <= 2)
    		{
    			int lenth = expand(all[s[i]], i, s);
    			if(max<lenth)
    			{
    				max = lenth;
    				left = all[s[i]] - lenth / 2 + 1;
    			}
    		}
    		all[s[i]] = i;
    	}
    	return s.substr(left, max);
    }
    };
    

    the case,for example,"babad".
    alt text
    alt text
    sorry for my bad English.


Log in to reply
 

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