Easy Solution CPP basic


#1

int Solution::solve(string A) {
int n = A.size();

int i = 0;
int j = n-1;
int cnt = 0;
while(i<=j){
    if(A[i] == A[j]) {
        i++; j--;
    }
    else{
        
        if(j == n-1){
            
            cnt++;
            i++;
        }
        
        else{
            
            cnt += (n-1-j);
            j = n-1;
        }
    }
}

return cnt;

}


#2

FYI, although your solution passes interviewbit, it is a wrong solution. It fails for input “aaashsaa”.
The answer should be 1 (append ‘a’ at the end), however your solution outputs 6.


#3

i think now it is ok
int Solution::solve(string A) {
int n = A.size();

int i = 0;
int j = n-1;
int cnt = 0;
while(i<=j){
if(A[i] == A[j]) {
i++; j–;
}
else{

    if(j == n-1){
        
        cnt++;
        i++;
    }
    
    else{
        cnt=cnt+1;
        
        i =i+j -n+2;
        j = n-1;
    }
}

}

return cnt;
}


#4

can you explain why you have written i=i+j-n+2