Spent 2.3 hours on a code, ends with TLC

When you get TLC's after spending 2.3 hours on the logic and the implementation of the problem.

/*** Python Version ***/
def isPalin(s):
    for i in range(len(s)):
        if s[i]!=s[len(s)-1-i]:
            return False
    return True
def give_max(s):
    '''Gives the max len of contiguous possible palindromic 
    substring of the given string'''
    c_len=0
    m_len=0
    for i in range(len(s)-1):
        for j in range(i+1,len(s)):
            c_len=0
            if(isPalin(s[i:j+1])):
                #Check if the string is a palindrome
                c_len=j+1-i
                if c_len>m_len:
                    m_i=i
                    m_j=j+1
                    m_len=c_len
#     return m_len,(s[m_i:m_j])
    return m_len
def rotate_str(s:str,k:int):
    return s[k:]+s[:k]

def circularPalindromes(s:str):
    tmp=""
    ans_ls=list()
    for i in range(len(s)):
        if i==0:tmp=rotate_str(s,0)
        if i!=0:tmp=rotate_str(tmp,1)
#         print("The tmp_str returned by 
the rotate_str func is ",tmp)
        ans_ls.append(give_max(tmp))
    return ans_ls

/*** Cpp Version ***/
string rotate(string s,int k){
    return s.substr(k)+s.substr(0,k);
}
//Func just to check is a string 
is palindrome or not
int isPalin(string s){
    int s_size=s.size();
    for(int i=0;i<s_size;i++){
        if(s[i]!=s[s_size-1-i]){
            return 0;
        }
    }
    return 1;
}
//Returns the max length palindromic 
contiguous substring possible
int foo(string s){
    int s_size=s.size();
    int c_len=0,m_len=0;
    for(int i=0;i<s_size-1;i++){
        for(int j=s_size-1;j>i;j--){
            if(isPalin(s.substr(i,j+1-i))){
                c_len=j+1-i;
                if(c_len>m_len){
                    m_len=c_len;
                }
            }
        }
    }
    return m_len;
}
//The main function that uses the above 
two funcs to do the overall task
vector<int> circularPalindromes(string s){
    int s_size=s.size();
    vector<int> ans;
    string tmp;
    for(int i=0;i<s_size;i++){
        if(i==0){
            tmp=rotate(s,0);
            ans.push_back(foo(s));
        }
        if(i!=0){
            tmp=rotate(tmp,1);
            ans.push_back(foo(tmp));
        }
    }
    return ans;
}



 

Comments

Popular Posts