What's wrong with my C++ for longest palindromic substring


  • 0
    T

    Hi, all,
    I got the following error of "wrong answer":
    Input: "ccc"
    Output: "ccc"
    Expected: "ccc"
    Please help me out, thanks tons.

        string longestPalindrome(string s) {
        int len = s.length();
        if(len < 2) return s;
        else if(len == 2) {
        	return s[0] == s[1]? s : "";
        }
        else{
        	string retStr = "";
        	int retStrLen = 0;
        	int currentIdx = 1;
        	
        	while( currentIdx < len ){
    
        		string tmpStr;    			
        		int tmpLen = 0;
    
        		if( s[currentIdx - 1] == s[currentIdx + 1] ){
        			if(tmpLen == 0) {tmpStr.append(1, s[currentIdx] ) ; tmpLen++;}
    
        		    for (int i = 1; i < (len - retStrLen); i++){
        			
    					if( s[currentIdx - i] == s[currentIdx + i] ){
        				
        					tmpStr.insert( 0, 1, s[currentIdx - i] );
        					tmpStr.append( 1, s[currentIdx + i] );
        					tmpLen += 2;        				
        				}
        				else{          				         				       				
        					break;
        				}
        			}
        		}
    
        		else if( s[currentIdx - 1] == s[currentIdx]  ){
        			for( ; tmpLen < len; ) { 
        				if (s[currentIdx - tmpLen/2 -1 ] == s[currentIdx + tmpLen/2]) {
        				
        					tmpStr.insert( 0, 1, s[currentIdx - tmpLen/2 -1] );
        					tmpStr.append(1, s[currentIdx + tmpLen/2] );
        					tmpLen += 2;
        				}
        				else{
        					break;
        				}
        			}
        		}
        		else{
        			;
        		}
    
        		if( tmpLen > retStrLen ){
        			retStr = tmpStr;
        			retStrLen = tmpLen;
        		} 
        		currentIdx++;
        	} // end of while
    
        	return retStr;
        }
    
        
    }

  • 0
    N

    Be careful about the index, it might be out of range:
    if( s[currentIdx - i] == s[currentIdx + i] )

    if (s[currentIdx - tmpLen/2 -1 ] == s[currentIdx + tmpLen/2])


Log in to reply
 

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