这是我下面的代码,用于检查给定字符串数组的字谜 即使在最简单的情况下,只有一个输入,它总是给我假 我不明白我没有正确地将字符串数组转换为字符串,或者我的算法是完全错误的。
public class anagram
{
static boolean isAnagram(String[] s1, String[] s2) {
String str = s1.toString();
String str2 = s2.toString();
if (str.length() != str2.length())
return false;
for (int i =0; i<str.length();i++)
{
for (int j = 0;j<str2.length();j++)
{
if (s1[i] == s2[j]) {
return true;
}
return false;
}
}
return true;
}
public static void main(String [] args){
String [] s1 = {"shot"};
String [] s2 = {"host"};
System.out.println(isAnagram(s1,s2));
}
}
你能帮我辨别出什么问题吗?
答案 0 :(得分:0)
字符串不是Java中的原始变量,因此您必须use the .equals()
method而不是使用&#39; ==&#39;来检查相等性。进行彻底的比较。
答案 1 :(得分:0)
您的检查算法似乎有点不正确
在此处编辑了isAnagram
函数:
public static void main(String[] args)
{
String s1 = "shotaabb";
String s2 = "hostbaba";
System.out.printf("String s1: %s, String s2: %s%n", s1, s2);
System.out.println(isAnagram(s1, s2) ?
"Is anagram" : "Is not an anagram");
}
static boolean isAnagram(String s1, String s2)
{
String str1 = new String(s1);
String str2 = new String(s2);
// Ensures that both strings are of the same length
if (str1.length() != str2.length())
return false;
int str1Len = str1.length();
for (int i = 0; i < str1Len; i++)
{
int charIndex = str2.indexOf(str1.charAt(i));
if(charIndex == -1) // Not found in str2
return false;
else
{
// Remove the character from str2
str2 = str2.substring(0, charIndex) +
str2.substring(charIndex + 1);
}
}
return true;
}
代码的作用是:
<强>输出:强>
String s1: shotaabb, String s2: hostbaba
Is anagram
更新(比较字符串数组):
String[] strArr1 = {"shot", "dcba"};
String[] strArr2 = {"host", "abcd"};
for(String s1 : strArr1)
{
for(String s2 : strArr2)
{
System.out.printf("%nString s1: %s, String s2: %s%n", s1, s2);
System.out.println(isAnagram(s1, s2) ?
"Is anagram" : "Is not an anagram");
}
}
更新代码的输出:
String s1: shot, String s2: host
Is anagram
String s1: shot, String s2: abcd
Is not an anagram
String s1: dcba, String s2: host
Is not an anagram
String s1: dcba, String s2: abcd
Is anagram
答案 2 :(得分:0)
d2 // ["3": {some 15}, "2": {some "two"}, "1": {some 1486228695.557882}, "4": {some true}]
答案 3 :(得分:0)
要检查两个字符串是否为字谜,大小写不敏感,此处为方法:
public boolean isAnagram(String s1, String s2) {
class SortChars{
String sort(String source) {
char[] chars = source.toLowerCase().toCharArray();
Arrays.sort(chars);
return new String(chars);
}
}
SortChars sc = new SortChars();
return sc.sort(s1).equals(sc.sort(s2));
}
解决方案取自“破解编码面试”一书,由Gayle Laakmann McDowell撰写