Palindrome Index

  • + 0 comments

    My C++ Solution: Time complexity = O(n)

    string canPalindrome(string s){
        bool op1 = false;
            int slow = 1;
            int fast = s.length()-1;
            cout << s <<endl;
            while(fast > slow){
                if(s[fast] != s[slow]){
                    op1 = true;
                }
                fast --;
                slow++;
            } 
            if(op1)return "second";
            else return "first";
    }
    
    int palindromeIndex(string s) {
        int idx = -1;
        int fast = s.length()-1;
        int slow = 0;
        
        while(slow < fast){
            if(s[slow] != s[fast]){
                string sub = s.substr(slow,(fast-slow)+1);
                string result = canPalindrome(sub);
                result == "first" ? idx=slow : idx = fast;
                return idx;
            }
            slow++;
            fast--;
        }
        return idx;
    }