正如您在标题中所看到的,我正在尝试编写一个程序,该程序可以为我解决“夜间标准管测验”。一部分。它必须能够在地铁站名称中找到字谜。我在互联网上找到了很多代码来检查两个词是否是字谜。但是我需要一些不同的东西:我想给程序提供伦敦所有地铁站的名称,并给它一个字谜以进行比较和检查,是否适合其中一个站名。我怎么做? 您会在下面看到我的“比较两个字”代码:
package anagram;
import java.util.Arrays;
public class anagram {
static void isAnagram(String str1, String str2) {
String s1 = str1.replaceAll("\\s", "");
String s2 = str2.replaceAll("\\s", "");
boolean status = true;
if (s1.length() != s2.length()) {
status = false;
} else {
char[] ArrayS1 = s1.toLowerCase().toCharArray();
char[] ArrayS2 = s2.toLowerCase().toCharArray();
Arrays.sort(ArrayS1);
Arrays.sort(ArrayS2);
status = Arrays.equals(ArrayS1, ArrayS2);
}
if (status) {
System.out.println(s1 + " and " + s2 + " are anagrams");
} else {
System.out.println(s1 + " and " + s2 + " are not anagrams");
}
}
public static void main(String[] args) {
isAnagram("Keep", "Peek");
isAnagram("Mother In Law", "Hitler Woman");
}
}
答案 0 :(得分:2)
简单:
keep
-> eekp
)。Peek
-> eekp
)并在您的收藏夹中进行搜索。示例:
public static String orderString(String candidate) {
char[] ccc = candidate
.replaceAll("[^\\p{IsAlphabetic}]", "")
.toLowerCase()
.toCharArray();
Arrays.sort(ccc);
return String.valueOf(ccc);
}
public static void main(String... args) {
Collection<String> tubeStations
= Arrays.asList("Acton Town",
"Acton Central", "Aldgate",
"Aldgate East", "Alperton",
"...");
Map<String, String> tubeMapAnagram = new java.util.LinkedHashMap<>();
for (String currCandidate: tubeStations) {
tubeMapAnagram.put(orderString(currCandidate), currCandidate);
}
String myCandidate = "Alpen Tor";
String foundOriginal = tubeMapAnagram.get(orderString(myCandidate));
if (foundOriginal!=null) {
System.out.println("anagram found for '"+foundOriginal+"'");
}
}
使用orderString()
方法,甚至可以简化您的原始示例。
boolean isAnagram(String str1, String str2) {
return Objects.equals(orderString(str1), orderString(str2));
}
答案 1 :(得分:1)
您的代码工作。您是否需要一种在列表中插入所有电台名称的方法?
public static void main(String[] args) {
String[] station = {"first", "second", "third", ..., "last"};
String check = "anagram";
for(int i=0; i < station.length(); i++){
isAnagram(station[i], check);
} }