3

我试图找出两个字符串是否是彼此的字谜:

void anagram(String a, String b) {
    List<Character> bcopy = new ArrayList<Character>();

    for (int i = 0; i < b.length(); i++)
        bcopy.add(b.charAt(i));
    if (b.length() == 0 || a.length() == 0) {
        System.out.println("Exit");
    } else {
        for (int i = 0; i < a.length(); i++) {
            char temp = a.charAt(i);
            if (bcopy.contains(temp)) {
                System.out.println("match found" + temp);
                bcopy.remove(temp);
            }
            for (char j : bcopy) {
                System.out.println("Values" + j);
            }
        }
    }
}

我在 remove() 行不断收到越界错误。有人可以告诉我在按对象可用性搜索时如何达到数组边界吗?我在这里想念什么?

4

3 回答 3

4

问题是您使用的是int-argument 版本,remove()因为char temp被视为int. 这是一个解决方法:

bcopy.remove(Character.valueOf(temp));

顺便说一句,测试字谜的更好方法是:

char[] c1 = a.toCharArray();
char[] c2 = b.toCharArray();

Arrays.sort(c1);
Arrays.sort(c2);

return Arrays.equals(c1, c2);  // true -> anagram, false -> not anagram
于 2013-09-12T00:33:21.317 回答
1

还有另一种算法可能更适合该任务。它计算等长字符串的字母频率。为简单起见,我假设所涉及的所有字符集都可以用常见的 8 位代码页之一表示。

void anagram(String a, String b) {
    int    freqa[256], freqb[256];

    if (b.length() == 0 || a.length() == 0) {
        System.out.println("Exit");
        return;
    }

    for (int i = 0; i < b.length(); i++) {
        freqa[(int) a.charAt(i)]++;
        freqb[(int) b.charAt(i)]++;
    }

    for (i = 0; i < 256; i++) {
        if (freqa[i] <> freqb[i]) {
            System.out.println("Exit");
            return;
        }
    }
    System.out.println("match found: '" + a + "', '" + b + "'");
}
于 2013-09-12T00:48:50.323 回答
1

你的代码有问题。您正在从列表中删除项目,但是循环运行“n”次是字符串长度为“n”。

因此,如果从列表中删除项目并且循环计数达到从列表中删除索引的数字,它将给出异常。您可以保留计数而不是删除项目。我稍微修改了你的代码,现在工作正常。

请检查

import java.util.ArrayList;
import java.util.List;

class Anagram{
void anagram(String a, String b) {
    List<Character> bcopy = new ArrayList<Character>();
    int count=0;

    for (int i = 0; i < b.length(); i++)
        bcopy.add(b.charAt(i));
    if (b.length() == 0 || a.length() != b.length()) {
        System.out.println("Two strings are not anagram");
    } else {
        for (int i = 0; i < a.length(); i++) {
            char temp = a.charAt(i);
            if (bcopy.contains(temp)) {
                //System.out.println("match found" + temp);
                //bcopy.remove(temp);-- Here list size was reduced but the loop was constant, because list size is less than a.length() now it was giving error
                //System.out.println(c);
                count++;
            }
        }
        if(count==a.length()) {
            System.out.println("Two strings are anagram");
        }
        else {
            System.out.println("Two strings are not anagram");
        }
    }
}
}

public class Test1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Anagram a=new Anagram();
        a.anagram("abs", "ass");
    }

}
于 2019-05-05T17:12:51.007 回答