Skip to content

Instantly share code, notes, and snippets.

@priyadarshitathagat
Created September 13, 2016 14:47
Show Gist options
  • Save priyadarshitathagat/e2a76ba05344b45cb21d0579eded814a to your computer and use it in GitHub Desktop.
Save priyadarshitathagat/e2a76ba05344b45cb21d0579eded814a to your computer and use it in GitHub Desktop.
To check whether a given string is Palindrome or not if not, check whether any of its 'ANAGRAM' is Palindrome or not with a complexity of O(N)
import java.io.*;
import java.util.*;
class palin_anagram
{
void str(String s)
{
char ch[]=s.toCharArray();
Arrays.sort(ch);
int l=s.length();
if(l%2==0)
evn(ch);
else
odd(ch);
}
void evn(char ch[])
{ int c=1;
for(int i=1; i<ch.length; i++)
{if(ch[i-1]==ch[i])
c++;
else if(c%2!=0)
{System.out.println("Not-Palindrome"); System.exit(0);}
else if(c%2==0)
c=1;
}
System.out.println("Palindrome");
}
void odd(char ch[])
{ int c=1,x=0;
for(int i=1; i<ch.length; i++)
{if(ch[i-1]==ch[i])
c++;
else if(c%2!=0)
x++;
else if(x>=2)
{System.out.println("Not-Palindrome"); System.exit(0);}
else if(c%2==0)
c=1;
}
System.out.println("Palindrome");
}
}
class ana
{public static void main(String [] args)throws IOException
{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
palin_anagram d=new palin_anagram();
String s=in.readLine();
d.str(s);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment