Why this code gives tle at testcase 59 ?

My approach is simple take two string prefix and suffix and match at every index from 1 to n-1 .

class Solution {
public:
    string longestPrefix(string s) {
        if(s.length()==1)
            return "";
        string prefix = "";
        string suffix = "";
        string ans = "";
        int n = s.length();
        for(int i=0;i<n-1;i++){
            prefix += s[i];
            suffix = s[n-i-1] + suffix;
            if(prefix==suffix)
                ans = suffix;
        }
        
        return ans;
    }
};
Comments (1)