Why is my code not working!?


  • 0
    A
    class Solution {
    public:    
        /**
         * @param source: A string
         * @param target: A string
         * @return: A string denote the minimum window
         *          Return "" if there is no such a string
         */
        string minWindow(string &source, string &target) {
            string minW;
            if (source.size() == 0 || target.size() == 0) {
                return minW;
            }
            
            vector<int> targetHash(256, 0);
            vector<int> sourceHash(256, 0);
            for (int i = 0; i < 256; i++) {
                targetHash[i] = 0;
                sourceHash[i] = 0;
            }
            int j = 0, i = 0;
            int currLen = INT_MAX;
            for (int k = 0; k < target.size(); k++) {
                targetHash[target[k]]++;
            }
            
            for (i = 0; i < source.size(); ++i) {
                while ((!valid(sourceHash, targetHash)) && (j < source.size())) {
                    sourceHash[int(source[j])]++;
                    if (j < source.size()) {
                        j++;
                    } else {
                        break;
                        
                    }
                }
                if (valid(sourceHash, targetHash)) {
                    if (currLen > (j - i)) {
                        if(j >=i )
                        currLen = min(currLen, j - i);
                        if (j > i)
                            minW = source.substr(i, j);
                        else if (j == i) {
                            minW = (source[i]);
                        }
                    }
                }
                sourceHash[int(source[i])]--;
            }
            return minW;
        }
    
    private:
        bool valid(vector<int>& sourceHash, vector<int>& targetHash) {
            
            for(int i = 0; i < 256; i++) {
                if(targetHash[i] > sourceHash[i])    
                    return false;
            }
            return true;
        }
    };
    

    If I changed declaration in JAVA is works flawlessly, but idk why it doesn't work in c++


Log in to reply
 

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