My solution runtime error~ for help and thx~


  • 0
    D
    class Solution {
    public:
    	string getHint(string secret, string guess) {
    		string result;
    		vector<int> overlap;
    		int a = 0, b = 0;
    		for (unsigned int i = 0; i<secret.size(); i++)
    		{
    			if (secret[i] == guess[i])
    			{
    				a++;
    				overlap.push_back(i);
    			}
    		}
    		result = to_string(a) + 'A';
    		string secret1 = secret;
    		string guess1 = guess;
    		for (auto l : overlap)
    		{
    			secret1.erase(secret1.begin() + l);
    			guess1.erase(guess1.begin() + l);
    		}
    		if (!secret1.empty())
    		{
    			for (unsigned int j = 0; j<secret1.size(); j++)
    			{
    				for (unsigned int k = 0; k<guess1.size(); k++)
    				{
    					if (j != k&&secret1[j] == guess1[k])
    					{
    						b++;
    						break;
    					}
    				}
    			}
    		}
    		result += to_string(b) + 'B';
    		overlap.clear();
    		return result;
    	}
    };
    

    VS2013 checked but this not, asking for the reason and solution, thx~


  • 1
    R

    This is happening because overlap contains the indexes in ascending order.

    Consider input "11", "11". In this case overlap will contain indices 0 and 1. When erasing characters from secret1 it will try to erase character 0 and then character 1, but there is no character 1 after character 0 was erased.

    You could reverse the first for loop to fix the RuntimeError:

    for (int i = secret.size() - 1; i>=0; i--)
    

Log in to reply
 

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