Why it got run-time error given input "abbacd", it works fine in other place.


  • 0
    Y
    class Solution {
    public:
    	string shortestPalindrome(string s) {
    		int len = s.size();
    		if (len == 0 || len == 1) return s;
    		int string_size = s.size();
    		int compare_len;
    		bool even;
    		bool satisfied;
    		while (true){
    			even = (len &1)==0;
    			compare_len = string_size - (even ? len / 2 : len / 2+1);
    			auto it_l = s.begin(), it_r = it_l;
    			it_l += len / 2 - 1;
    			it_r = even ? it_l + 1 : it_l + 2;
    			satisfied = true;
    			
    			while (compare_len > 0){
    				if (*it_l != *it_r){
    					satisfied = false;
    					break;
    				}
    				--it_l;
    				++it_r;
    				--compare_len;
    			};
    			if (satisfied){
    				for (; it_l != s.begin(); --it_l)s.push_back(*it_l);
    				s.push_back(*it_l);
    				break;
    			}
    			len++;
    		}
    		return s;
    	}
    };

Log in to reply
 

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