What's wrong with my code?


  • 0
    H
    class Solution {
    public:
        string removeDuplicateLetters(string s) {
    		string result;
    		map<char, int> cmap;
    		
    		for (unsigned int i = 0; i < s.size(); ++i)
    			cmap[s[i]] ++;
    		
    		for (unsigned int i = 0; i < s.size(); ++i) {
    			cmap[s[i]] --;
    			
    			if (result.find(s[i]) != string::npos)
    				continue;
    			
    			while (s[i] < result.back() and cmap[result.back()])
    				result.pop_back();
    
    			result += s[i];
    		}
    		return result;
    	}
    };
    

    I got run time error. But when I tested the last input, it could generate the expected result. Please suggest, thanks


  • 0
    S

    debug with try/catch, I got an IndexError. An undefined behavior? Just modify your code, now it work:

    BEFORE:

     while (s[i] < result.back() && cmap[result.back()]) {
    

    AFTER:

     while (!result.empty() && s[i] < result.back() && cmap[result.back()]) {

  • 0
    H

    Thank you very much!


Log in to reply
 

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