Java程序检查给定的字符串是否为异序词
时间:2020-01-09 10:35:32 来源:igfitidea点击:
在这篇文章中,我们将看到一个Java程序来检查给定的字符串是否为anagram。如果我们可以通过重新排列另一个字符串中的所有字母来获得第二个字符串,则两个字符串称为异序词 anagram。
例如, Keep 和 Peek, Dormitory 和 Dirty room, Listen 和 Silent
可以使用以下逻辑来编写用于检查给定字符串是否为anagram的Java程序
- 通过对字符串进行排序–如果在删除空格后对两个字符串都进行了排序。然后,两个字符串应该相等。
- 通过迭代–我们可以迭代一个字符串,然后搜索另一个字符串中的每个字符,如果每个字符在第二个字符串中一次被找到,则该字符串为字谜。
使用排序逻辑检查字谜的Java程序
import java.util.Arrays;
public class AnagramStrings {
public static void main(String[] args) {
checkIfAnagram("Dormitory", "Dirty room");
checkIfAnagram("fried", "fired");
checkIfAnagram("friend", "fried");
}
private static void checkIfAnagram(String str1, String str2){
boolean flag;
// replace all spaces
String firstString = str1.toLowerCase().replaceAll("\s", "");
String secondString = str2.toLowerCase().replaceAll("\s", "");
if(firstString.length() != secondString.length()){
flag = false;
}else{
// sort and compare strings
firstString = sort(firstString);
secondString = sort(secondString);
flag = firstString.equals(secondString);
}
if(flag){
System.out.println(str1 + " and " + str2 + " are anagrams");
}else{
System.out.println(str1 + " and " + str2 + " are not anagrams");
}
}
// Method for sorting the string
private static String sort(String str) {
char[] charArray = str.toCharArray();
Arrays.sort(charArray);
return new String(charArray);
}
}
输出:
Dormitory and Dirty room are anagrams fried and fired are anagrams friend and fried are not anagrams
使用迭代逻辑检查字谜的Java程序
我们可以使用迭代逻辑来检查给定的字符串是否为字谜。为此,我们需要按char迭代字符串char中的一个,并在第二个字符串中搜索相同的char。第一个字符串的每个字符都应在第二个字符串中。
确保如果找到字符,也会从第二个字符串中删除该字符。如果第一个字符串中的任何字符出现多次,则不这样做将导致再次匹配同一字符。
public class AnagramStrings {
public static void main(String[] args) {
checkIfAnagram("The eyes", "they see");
checkIfAnagram("peek", "keep");
checkIfAnagram("friend", "fried");
}
private static void checkIfAnagram(String str1, String str2){
boolean flag = true;
int index;
// replace all spaces
String firstString = str1.toLowerCase().replaceAll("\s", "");
String secondString = str2.toLowerCase().replaceAll("\s", "");
// length check
if(firstString.length() != secondString.length()){
System.out.println(str1 + " and " + str2 + " are not anagrams");
return;
}
char[] strArray = firstString.toCharArray();
StringBuilder sb = new StringBuilder(secondString);
for(char c : strArray){
// search for char in second String
index = sb.indexOf(""+c);
// If char is found delete it from the second string
// so that there is no false match for the similar char
if(index != -1){
sb.deleteCharAt(index);
}else{
flag = false;
break;
}
}
if(flag){
System.out.println(str1 + " and " + str2 + " are anagrams");
}else{
System.out.println(str1 + " and " + str2 + " are not anagrams");
}
}
}
输出:
The eyes and they see are anagrams peek and keep are anagrams friend and fried are not anagrams

