Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- We can solve this problem efficiently in O(n) time and O(1) space.
- Approach : Take left pointer as 0 and right and n-1 and compare both characters
- If both are same left++ and right–;
- else
- we can think that we have to add N-right elements at front to make last (N-right) characters palindrome so added = (n-right)
- Now left again point to 0 as we have to check the string from 0th index .
- but while the character at right position is same as 0th index char then we can add one less character at front and left will increase by 1.
- '''
- class Solution:
- # @param A : string
- # @return an integer
- def solve(self, a):
- n=len(a)
- l,r=0,n-1
- added =0
- while l<r:
- if a[l]==a[r]:
- l,r=l+1,r-1
- else:
- l=0
- added=n-r #we will add a[r:][::-1] to start
- while a[l]==a[r]:#this while loop decreases the redundant characters that we added which already useful in making palindrome
- l=l+1
- added-=1
- r-=1#Finally we should reduce the actual r because we have added sufficent chracters from back
- return added
- '''
- e.g. a c a a
- | |
- a c a a
- | |
- a a =a c a a #Before equal we added required chraracters to make it palindrome
- | |
- a a =a c a a
- x | |
- final a a c a a
- added =1
- '''
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement