Mon Sep 05, 2011 6:45 am
Thu Sep 08, 2011 11:49 pm
import java.io.IOException;
public class ExampleClass {
static int sizeOne;
static int count;
static char[] firstCharArray;
static char[] secondCharArray;
public static void main(String[] args) throws IOException {
String firstString = "Java";
String secondString = "Jvaa";
sizeOne = firstString.length();
count = 0;
firstCharArray = new char[sizeOne];
secondCharArray = new char[sizeOne];
// assumption both are equal in size.
for (int j = 0; j < sizeOne; j++) {
firstCharArray[j] = firstString.charAt(j);
secondCharArray[j] = secondString.charAt(j);
}
startAnagram(sizeOne);
System.out.println("The strings are not anagram ");
}
// recursive anagram algorithem
public static void startAnagram(int stringSize) {
if (stringSize == 1) {
return;
}
for (int i = 0; i < stringSize; i++) {
startAnagram(stringSize - 1);
if (stringSize == 2) // if innermost,
{
print();
}
rotateAnagram(stringSize); // rotate word
}
}
// rotate left all chars from position to end
public static void rotateAnagram(int currentSize) {
int i;
int position = sizeOne - currentSize;
// temp for current letter.
char temp = firstCharArray[position];
//shift others left
for (i = position + 1; i < sizeOne; i++) {
firstCharArray[i - 1] = firstCharArray[i];
}
//put first on right
firstCharArray[i - 1] = temp;
}
public static void print() {
for (int i = 0; i < sizeOne; i++) {
System.out.print(firstCharArray[i]);
}
System.out.println("");
checkIfStringsEqual();
}
public static void checkIfStringsEqual() {
boolean flag = true;
for (int i = 0; i < sizeOne; i++) {
if (firstCharArray[i] != secondCharArray[i]) {
flag = false;
break;
}
}
if (flag) {
System.out.println("The strings are anagram ");
System.exit(1);
}
}
}
Fri Sep 16, 2011 1:35 pm
public static void main(String[] arg) {
String str1 = "hello";
String str2 = "olleh";
if (isAnagram(str1, str2)) {
System.out.println("Anagram");
} else {
System.out.println("Not Anagram");
}
}
private static boolean isAnagram(String str1, String str2) {
if (str1.length() != str2.length()) return false;
for (int i = 0; j = str2.length() -1; i <= j; i++, j--) {
if (str1.charAt(i) != str2.charAt(j)) {
return false;
}
}
return true;
}
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.