Lets say i have "jfk" and "jfc". I want to iterate through both strings and find out if and where they differ. I am trying to see if the strings are anagrams. "new door" and "one word" are anagrams. If its not an anagram i want the code to tell me by how many characters the strings differ. The jfk and jfc differ by 1. "macd" and "mebc" differ by 2 and they cant be anagrams. If the two strings are different lengths then they can't be anagrams.
I tried iterating through the strings but that's when i got stuck. I have no idea how to iterate through both strings at the same time and find out how if they differ by certain characters or not. I only got as far as checking if both strings were the same length.
static void isAnagram(List <String> s1, List <String> s2) {
if (s1.length() != s2.length()) {
System.out.println("Not anagrams");
} else {
for(int i = 0; i < s1.length(); i++) {
for(int j = 0; j < s2.lenth(); j++) {//i know that iterating through both strings like this does not make sense but i am stuck.
}```
Convert the arrays to char arrays. Then sort the arrays alphabetically after that compare them character by character.
String str = "abc";
char[] chars = str.toCharArray();
you can use this to convert string to char array,next it will be very easy loop the char array by running a simple if condition and increment a variable which will tell the difference of words.
If you are allowed additional libraries, you should have a look at Google’s Guava, espacially at com.google.common.collect.Multiset<E> and it’s implementations. You can put the characters of each string into an Multiset<Character> (not a Multiset, that will not work, as E must be a reference type, no primitive). Both strings are anagrams if multiset1.equals(multiset2).
Of both for loops, it seems to me that you only need one of the loop and use the same counter for both strings?
Related
I printed 2 strings and they are literally identical, no whitespaces cause i replaced them.
https://ideone.com/cw07LG
Here it is compiled
public class Palindrome{
public static boolean isPalindrome(String word){
int length;
String oppositeWord ="";
word = word.replace(" ","");
word = word.toLowerCase();
length = word.length();
for(int i=length-1;i>=0;i--){
if(Character.isLetter(word.charAt(i))){
oppositeWord +=word.charAt(i);
}else{
word = word.replace(word.charAt(i),'\0');
}
}
System.out.println(oppositeWord);
System.out.println(word);
return oppositeWord.equals(word);
}
public static void main(String[]args){
System.out.println(isPalindrome("Madam, I'm Adam"));
}
}
First, Java Strings are immutable and should not be manipulated character by character (that is why the Java Library has the StringBuilder and StringBuffer classes).
Second, Java Strings are not really equivalent to char[] in C/C++. They are more like char* in that they point to some other memory that holds the actual information. Changing the non-alphabetic characters to '\0' null characters is not deleting them from the string. They are not printed on the screen, but still exist in memory. (That is one way Java Strings are different from C/C++ strings ... Java Strings are not null terminated arrays of characters!)
If you add some print statements to print the length, you will find that the oppositeWord is two characters smaller than word.
System.out.println(oppositeWord.length()); // prints 11
System.out.println(word.length()); // prints 13
To really make the two Strings equal, the same characters replaced in word must also be inserted in oppositeWord at the same indices or removed altogether from both. i.e.
for(int i=length-1;i>=0;i--) {
if(Character.isLetter(word.charAt(i))) {
oppositeWord +=word.charAt(i);
} else {
word = word.replace(word.charAt(i),'\0');
oppositeWord += word.charAt(i); // << This line!
}
}
Now, both Strings will contain the same information and oppositeWord.equals(word) will hold.
Also FYI, StringBuilder and StringBuffer both have reverse() methods that could be used to simplify this process.
Replacing a character with '\0' is not the same thing as removing the character all together. It won't show up when you print it, so they will look the same, but it's still there and will make them not equal.
Try printing the lengths along with the words.
This line is wrong:
word = word.replace(word.charAt(i),'\0');
Replacing a character by \0 isn't the same as removing it. You want something like this:
word = word.replace(""+word.charAt(i), "");
However, like this comment says, there are better ways to check if a word is a palindrome.
Also, I'm not sure why, but your ideone.com shows a different output from my IDE (NetBeans). Yours shows:
madamimadam
madamimadam
false
But as Qbrute points out, the output is:
madamimadam
madam i madam
false
Which explains why the result is false. My best guess is that your on-line IDE has some trouble converting the \0 you added into text and just doesn't print anything.
It is true as mentioned by bluemoon93 that the two strings are actually not equal. The original string is madam i madam. This means it consists of spaces that makes the two strings different. I would suggest that you remove punctuation, spaces from the original string using regex. This will remove any extra spaces or punctuation.
public boolean isPalindrome(String word){
int length;
String oppositeWord ="";
word = word.toLowerCase();
length = word.length();
String newword = word.replaceAll("[\\s\\p{Punct}]", "");
for(int i=length-1;i>=0;i--){
if(Character.isLetter(word.charAt(i))){
oppositeWord +=word.charAt(i);
}
}
System.out.println(oppositeWord);
System.out.println(newword);
return oppositeWord.equals(newword);
}
The return result will now return true, since both strings are equal as they are matched by valid character and do not contain space or punctuation.
I'm trying to make a basic program where it checks if a word is a palindrome, and I need to figure out how to do two things.
How do I figure out how many letters are in a string?
and
How do I compare two chars to see if they are the same?
Thanks in adv.
How do I figure out how many letters are in a string?
String in Java is immutable object which means it does not change. So the following code creates new string every time it is needed:
String s = "Hello";
s += " World";
After above introduction the answer to question nr 1 is
int len = s.length();
How do I compare two chars to see if they are the same?
String has access method for its characters, that you can use to access and compare them:
char one = s.charAt(0);
char two = s.charAt(1);
if (one == two) {
:
}
For your assignment I would recommend to use public char[] toCharArray() method and loop the array for accessing each character.
1.) StringName.length() <- Java has a method that will return the length of the string
2.) charName == charName2 <- primitive type can use the comparison operator
You have some good ideas that will help you write a palindrome program. I will offer no hints though so you can figure it out. good luck. <-Taken (bad guy) voice
Suppose I have a polynomial -x^2 + 2x - 1 = 0. It is read from a file.
I have the code that analyzes each character of the polynomial.
I want to create an extra step that compacts the polynomial(so the white spaces gets eliminated) so I can check if the string is in fact a polynomial which I can easily do by just checking the last 2 index of the polynomial which is the equal sign and the zero like this: (=0)
Problem is some polynomial length have different lengths which gave me the thought to use an ArrayList. Problem is I cannot declare my ArrayList to be of type Character to store each character in the sequential index of an ArrayList.
public void createEquationNoWhiteSpaces(){
// it cannot be done because there is no ArrayList of characters
textArrayList = new ArrayList<String>();
for(int i = 0; i < text.length(); i++){
// Store the characters of the polynomial in an ArrayList
// because each polynomial has different length
if(text.charAt(i) != ' ')
textArrayList = text.charAt(i);
}
}
If you want to use an array, you can certainly declare an ArrayList<Character>. However, you might want to use a StringBuilder instead of a list for this purpose anyway.
st.replaceAll("\\s","")
removes all whitespace in string st
My question is that, I have 2 strings, say String1 & String2. Now I want to check whether these 2 strings contain same characters or not, irrespective of their sequence.
Suppose String1= "qwerty", String2= "qywter". Now these Strings contain same characters but are in different sequence. So is there any function that can be used to show that these strings contain same characters?? Can equals() method do that???
All help is appreciated.
char[] chars1 = string1.toCharArray();
char[] chars2 = string2.toCharArray();
Arrays.sort(chars1);
Arrays.sort(chars2);
return Arrays.equals(chars1, chars2);
It depends whether you actually want characters or you really want code points, and then it matters whether you want to count duplicates or not. Here's one solution:
public class a {
public static void main(String[] args) {
String s1 = "qwerty";
String s2= "qywter";
System.out.println(codePointSet(s1).equals(codePointSet(s2)));
}
public static Set<Integer> codePointSet(String s) {
Set<Integer> set = new TreeSet<Integer>();
for (int i = 0, cp; i < s.length(); i += Character.charCount(i)) {
cp = s.codePointAt(i);
set.add(cp);
}
return set;
}
}
You can use String.equals, albeit indirectly. First you need a helper method:
// given a String, sorts its chars and return it as another String
public static String sorted(String s) {
char[] arr = s.toCharArray();
Arrays.sort(arr);
return new String(arr);
}
Then you can have:
String s1 = "qwerty";
String s2 = "qywter";
System.out.println(sorted(s1)); // eqrtwy
System.out.println(sorted(s1).equals(sorted(s2))); // true
Note that this is not the most efficient algorithm -- it's O(N log N) time, and uses extraneous space -- but should work fine for short strings. For long strings, you'd want to go through each char (or Unicode code points) manually (instead of toCharArray()), and perhaps use the linear-time counting sort.
If you don't care about specific character counts matching (e.g. "xxxyyy" and "xy" has the same chars, albeit in different numbers), then you can use a set-like representation (java.util.BitSet).
// given a string, returns its used char set as a java.util.BitSet
public static BitSet usedChar(String s) {
BitSet bs = new BitSet();
for (int i = 0; i < s.length(); i++) {
bs.set(s.charAt(i));
}
return bs;
}
Then you can have:
System.out.println(
usedChar("xxxyyy").equals(usedChar("xy"))
); // true
System.out.println(
usedChar("xyz").equals(usedChar("abc"))
); // false
int[] f = new int[(int)char.MaxValue];
foreach (var c in string1) f[(int)c]++;
foreach (var c in string2) f[(int)c]--;
return f.Max() == 0 && f.Min() == 0;
This is preferable solution when string1.length() >> char.MaxValue and it has lower big O notation complexity.
EDIT this is actually C# code but you can easly achieve similar result in Java.
String.equals() won't work for your particular case. You will likely need to write your own method to equate strings in this way.
If you have a long string that you need to compare, and you don't need a guarantee of success, you can do something like this:
make sure the strings are the same length
for each image
add up all the characters (casted as ints)
add up squares of characters (again casted as ints)
compare the sums of squares and the sums
if they are the same, then the strings contain the same characters.
Actually I spent some time trying to figure out where this wouldn't work, but I can't think of one. My gut tells me I'm missing something here, or this is a good comparator for this case.
Two steps are require
Do xor of both strings and if xor is 0 then you are partially sure.
If xor is 0 then find the sum of ascii value of both strings and if ascii sum is same then
both strings are same.
Hope this helps
I'm using this piece of Java code to find similar strings:
if( str1.indexof(str2) >= 0 || str2.indexof(str1) >= 0 ) .......
but With str1 = "pizzabase" and str2 = "namedpizzaowl" it doesn't work.
how do I find the common substrings i.e. "pizza"?
Iterate over each letter in str1, checking for it's existence in str2. If it doesn't exist, move on to the next letter, if it does, increase the length of the substring in str1 that you check for in str2 to two characters, and repeat until no further matches are found or you have iterated through str1.
This will find all substrings shared, but is - like bubble sort - hardly optimal while a very basic example of how to solve a problem.
Something like this pseudo-ish example:
pos = 0
len = 1
matches = [];
while (pos < str1.length()) {
while (str2.indexOf(str1.substring(pos, len))) {
len++;
}
matches.push(str1.substring(pos, len - 1));
pos++;
len = 1;
}
If your algorithm says two strings are similar when they contain a common substring, then this algorithm will always return true; the empty string "" is trivially a substring of every string. Also it makes more sense to determine the degree of similarity between strings, and return a number rather than a boolean.
This is a good algorithm for determining string (or more generally, sequence) similarity: http://en.wikipedia.org/wiki/Levenshtein_distance.