10

我想做字谜算法,但这段代码不起作用。我的错在哪里?例如 des 和 sed 是字谜,但输出不是字谜 同时我必须使用字符串方法。不是数组。:)

public static boolean isAnagram(String s1 , String s2)
{
    String delStr="";
    String newStr="";

    for(int i=0;i<s1.length();i++)
    {
        for(int j=0 ; j < s2.length() ; j++)
        {
            if(s1.charAt(i)==s2.charAt(j))
            {
                delStr=s1.substring(i,i+1);
                newStr=s2.replace(delStr,"");
            }
        }           
    }

    if(newStr.equals(""))
        return true;
    else
        return false;
}
4

35 回答 35

31

一种更简单的方法可能是对两个字符串中的字符进行排序,然后比较它们是否相等:

public static boolean isAnagram(String s1, String s2){

        // Early termination check, if strings are of unequal lengths,
        // then they cannot be anagrams
        if ( s1.length() != s2.length() ) {
            return false;
        }
        s1=s1.toLowerCase();
        s2=s2.toLowerCase();
        char[] c1 = s1.toCharArray();
        char[] c2 = s2.toCharArray();
        Arrays.sort(c1);
        Arrays.sort(c2);
        String sc1 = new String(c1);
        String sc2 = new String(c2);
        return sc1.equals(sc2);
}

我个人认为它比嵌套的 for-loops =p 更具可读性

这具有O(n log n)运行时复杂度,其中n是较长字符串的长度。

编辑:这不是最佳解决方案。请参阅@aam1r 的答案以了解最有效的方法(即您应该在面试中实际说的话)

于 2012-12-03T21:46:31.143 回答
30

这可以使用恒定空间在线性时间内完成。这是帮助您入门的伪代码:

// Create new hashtable/hashmap to keep track of how many times each character
// is being used
character_map -> new hash map

// Initial check. If lengths are not the same, they can't be anagrams.
if s1.length != s2.length:
    throw exception "Not anagrams"

// Add all characters from s1 to hashmap. Increment the value to keep track of
// number of occurences
foreach character c1 in s1:
    character_map[c1]++

// Iterate through all character in s2 and decrement count of each character.
foreach character c2 in s2:
    character_map[c2]--

// If they are anagrams, each character should be at "0" count at the point.
// If we come across a character that is not, it means that they are not anagrams
foreach key k, value v in character_map:
    if v != 0:
            throw exception "Not anagrams"

此代码不排序,因此可以使用简单的循环来完成。总运行时间为 O(n),总空间为 O(1)——因此是最快的解决方案。您可以在哈希图中拥有的元素数量是恒定的(即您知道字母集中有多少项目)。

于 2012-12-03T22:04:48.550 回答
9
if(s1.charAt(i)==s2.charAt(j))
        delStr=s1.substring(i,i+1);
        newStr=s2.replace(delStr,"");

这段代码很好地展示了为什么你应该总是curly braces在你的 . 周围if有,即使只有一个语句。你的第二个任务实际上是在 , 之外if-condition并且总是会发生。

检查两个字符串的最佳方法Anagram是将它们转换为字符数组(String#toCharArray)。然后使用Arrays.sort方法对它们进行排序。并对它们进行比较。


更新 : -

如果您只想使用String方法,那么您实际上不需要嵌套循环。你可以只用一个。

这是您修改后的代码:-

public static boolean isAnagram(String s1 , String s2){

    if (s1.length() != s2.length()) {
        return false;
    }

    for(int i = 0; i < s2.length(); i++) {

            if( !s1.contains("" + s2.charAt(i))) {
                return false;
            }

            s1 = s1.replaceFirst("" + s2.charAt(i), "");
            s2 = s2.replaceFirst("" + s2.charAt(i), "");
    }
    return true;
}
于 2012-12-03T21:42:08.650 回答
8

更有效的是按排序顺序比较字符串。

public static boolean isAnagram(String s1 , String s2) {
    return s1.length() == s2.length() 
        && checkSum(s1) == checkSum(s2)
        && Arrays.equals(lettersSorted(s1), lettersSorted(s2));
}

static long checkSum(String s) {
    long sqrSum = 0;
    for(int i = 0; i < s.length(); s++) {
       char ch = s.charAt(i);
       sqrSum += ch + (1L << ch);
    }
}

static char[] lettersSorted(String s) {
    char[] chars = s.toCharArray();
    Arrays.sort(chars);
    return chars;
}

这是一个 O(N ln N) 算法,但如果字符串通常不是字谜,则平均为 O(N)。

于 2012-12-03T21:47:04.663 回答
7

我不确定您要做什么,但我很确定它不会起作用(并且它会在O(n^2).O(n log n)

public static boolean isAnagram(String s1, String s2){
  if (s1.length() != s2.length()) return false;

  char[] c1 = s1.toCharArray();
  char[] c2 = s2.toCharArray();

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

  for(int i = 0; i < c1.length; i++) {
    if(c1[i] != c2[i]) return false;
  }

  return true;
}
于 2012-12-03T21:47:59.897 回答
5

确定字符串是否为 Anagram 有多种可能的解决方案。1.使用Array.sort()预定义的方法

String string1 = "abc";
String string2 = "bca";
char[] chars = string1.toCharArray();
char[] chars2 = string2.toCharArray();
Arrays.sort(chars);
Arrays.sort(chars2);
string1 = new String(chars);
string2 = new String(chars2);
if (string1.equalsIgnoreCase(string2)) {
  System.out.println("Anagram");
} else {
  System.out.println("Not Anagram");
}

时间复杂度:Ω(n log n) 2.通过迭代法

char [] charArray = str.toCharArray();
if(str.length() == str1.length()){
    for(char ch : charArray){
        if(str1.indexOf(ch) == -1){
            System.out.println("Not Anagram");
        } 
    }    
    System.out.println("Anagram");
} else {
    System.out.println("Not Anagram");
}

时间复杂度:Ω(n)

虽然,第一个算法更具可读性,第二个算法确实执行得更快。

于 2019-02-27T05:51:50.847 回答
3

它不起作用的原因:

以“des”和“sed”为例。

在匹配的最后一次迭代中,它将评估:

if(s1.charAt(i)==s2.charAt(j))
{
    delStr=s1.substring(i,i+1);
    newStr=s2.replace(delStr,"");
}

这将是: if( "s" == "s" )

然后它将进入 if 块,并评估

newStr = "sed".replace("s","");

这会给你“ed”,而不是一个空字符串。

这个故事的寓意是,你总是从 s2 中替换字符减去一个字符,这永远不会是空的。

无论如何,使用 String.replace() 是不好的,因为默认情况下它将替换字符的所有实例。使用 String.replace(),它会将“sed”视为“seeeeeeed”的字谜。你最好使用 String.replaceFirst()。

无论如何,出发点是进行以下修改:

String newStr = s2;
...
// inside if block
newStr = newStr.replaceFirst( delStr, "" );
于 2012-12-03T22:05:12.350 回答
3
import java.util.Scanner;

public class Anagrams {

static boolean isAnagram(String a, String b) {
    a = a.toLowerCase();
    b = b.toLowerCase();
    if (a.length() != b.length()) {
        return false;
    }

    char[] chars = a.toCharArray();
    for (char c : chars) {
        int index = b.indexOf(c);
        if (index != -1) {
            b = b.substring(0, index) + b.substring(index + 1, b.length());
        } else {
            return false;
        }
    }
    return b.isEmpty();
}

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    String a = scan.next();
    String b = scan.next();
    scan.close();
    boolean ret = isAnagram(a, b);
    System.out.println((ret) ? "Anagrams" : "Not Anagrams");

    }
}
于 2018-10-05T06:46:24.807 回答
3

下面是一个简洁的代码片段,它在两个字符串的单次迭代以及 256 个元素数组的最终迭代中确定两个字符串是否是字谜。这种方法避免了对字符串中的字符进行排序以及通过在映射数组中记录字符计数来转换字符串/字符数组。

static boolean isAnagram(String s1, String s2) {
    if (s1.length() != s2.length()) return false;
    int n = s1.length();
    int[] charMap = new int[256];
    for (int i = 0; i < n; i++) {
        char c1 = s1.charAt(i);
        charMap[c1]++;
        char c2 = s2.charAt(i);
        charMap[c2]--;
    }
    for (int i = 0; i < charMap.length; i++) {
        if (charMap[i] != 0) return false;
    }
    return true;
}

此代码基本上递增和递减对应于字符的数组中的索引位置。如果任何数组元素在迭代结束时不为零,则增量和减量的数量不相等,因此字符串包含不同的字符并且不能是彼此的字谜。

鉴于此算法迭代两个相同大小的字符串一次,运行时间为 O(n)。空间复杂度为 O(1),因为 charMap 始终根据字符集要求保持不变。

于 2015-08-21T23:58:10.723 回答
2
public boolean checkAnagram(String s, String t) {
    s = s.toLowerCase();
    t = t.toLowerCase();

    // We can ignore blanks
    char[] word1 = s.replaceAll("\\s","").toCharArray();
    char[] word2 = t.replaceAll("\\s","").toCharArray();

    // Anagrams length should be the same
    if (word1.length != word2.length) {
        return false;
    }

    // Sorting arrays is pretty fast, it can be O(logn) 
    Arrays.sort(word1);
    Arrays.sort(word2);

    if (Arrays.equals(word1, word2)) {
        return true;
    }

    return false;
}
于 2019-01-27T19:27:07.150 回答
1

O(n) 解决方案,无需任何排序且仅使用一张地图。还添加了其他解决方案中缺少的正确空检查。

public boolean isAnagram(String leftString, String rightString) {
  if (leftString == null || rightString == null) {
    return false;
  } else if (leftString.length() != rightString.length()) {
    return false;
  }

  Map<Character, Integer> occurrencesMap = new HashMap<>();

  for(int i = 0; i < leftString.length(); i++){
    char charFromLeft = leftString.charAt(i);
    int nrOfCharsInLeft = occurrencesMap.containsKey(charFromLeft) ? occurrencesMap.get(charFromLeft) : 0;
    occurrencesMap.put(charFromLeft, ++nrOfCharsInLeft);
    char charFromRight = rightString.charAt(i);
    int nrOfCharsInRight = occurrencesMap.containsKey(charFromRight) ? occurrencesMap.get(charFromRight) : 0;
    occurrencesMap.put(charFromRight, --nrOfCharsInRight);
  }

  for(int occurrencesNr : occurrencesMap.values()){
    if(occurrencesNr != 0){
      return false;
    }
  }

  return true;
}

和不太通用的解决方案,但更快一点:

public boolean isAnagram(String leftString, String rightString) {
  if (leftString == null || rightString == null) {
    return false;
  } else if (leftString.length() != rightString.length()) {
    return false;
  }

  char letters[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
  Map<Character, Integer> occurrencesMap = new HashMap<>();
  for (char l : letters) {
    occurrencesMap.put(l, 0);
  }

  for(int i = 0; i < leftString.length(); i++){
    char charFromLeft = leftString.charAt(i);
    Integer nrOfCharsInLeft = occurrencesMap.get(charFromLeft);
    occurrencesMap.put(charFromLeft, ++nrOfCharsInLeft);
    char charFromRight = rightString.charAt(i);
    Integer nrOfCharsInRight = occurrencesMap.get(charFromRight);
    occurrencesMap.put(charFromRight, --nrOfCharsInRight);
  }

  for(Integer occurrencesNr : occurrencesMap.values()){
    if(occurrencesNr != 0){
      return false;
    }
  }

  return true;
}
于 2014-02-04T13:05:53.213 回答
1
Using HashMap
public boolean isAnagram(String word, String anagram) {
    if (word.length() != anagram.length())
        return false;

    int count = 0;
    Map<Character, Integer> map = new HashMap<>();

    for (int i = 0; i < word.length(); i++) {
        if (!map.containsKey(word.charAt(i)))
            map.put(word.charAt(i), 1);
        else
            map.put(word.charAt(i), map.get(word.charAt(i)) + 1);
    }

    for (int i = 0; i < anagram.length(); i++) {
        if (!map.containsKey(anagram.charAt(i)))
            return false;
        else if (map.get(anagram.charAt(i)) >= 1)
            map.put(anagram.charAt(i), map.get(anagram.charAt(i)) - 1);
        else
            return false;
    }

    return true;
}
于 2019-08-22T03:03:41.727 回答
0

这是一个更简单的方法,主要依赖于 java 完整的代码在这里https://github.com/rdsr/algorithms/blob/master/src/jvm/misc/AnagramsList.java(注意这解决了一个相关的不同问题)

class Anagram {
    Map<Character, Integer> anagram;

    Anagram(String s) {
        anagram = new HashMap<Character, Integer>();

        for (final Character c : s.toCharArray()) {
            if (anagram.containsKey(c)) {
                anagram.put(c, 1 + anagram.get(c));
            } else {
                anagram.put(c, 1);
            }
        }
    }

    @Override
    public int hashCode() {
        //.. elided
    }

    @Override
    public boolean equals(Object obj) {
        //.. elided
    }
}


    public class Anagrams {
            public static void main(String[] args) {
                System.out.println(new Anagram("abc").equals(new Anagram("bac")));
            }
        }
于 2014-04-12T06:32:56.010 回答
0

原因很简单,因为 replace 函数创建了一个新String对象。它对实际字符串(在您的情况下)没有任何作用s2,因为在 Java 中,字符串本质上是最终的。因此,正如 cmonkey 所指出的,您总是从字符串 s2 中删除一个字符,但实际上String创建的新对象少了 1 个字符,s2 保持原样。

在你的情况下让它工作的简单方法是创建一个新的字符串对象并将其分配给你自己。

{
    s2=s2.replace(delString,"");
    ....
    if(s2.empty()) return true;
    return false;
}
于 2014-07-26T20:20:45.733 回答
0

只是确保,您正在尝试检查 s1 是否是 s2 的字谜正确?这也意味着 s2 是 s1 的字谜。所以我只会对 s1 和 s2 进行排序并检查它们是否相等。

String string1 = "fdafdas";
String string2 = "fdwqkjl";
char[] chars = string1.toCharArray();
char[] chars2 = string2.toCharArray();
Arrays.sort(chars);
Arrays.sort(chars2);
string1 = new String(chars);
string2 = new String(chars2);
if (string1.equals(string2)) {
    //They are an anagram
}
于 2012-12-03T21:54:05.680 回答
0

使用位向量方法处理字谜子串的更快版本

public boolean isAnagram(String _source1, String _source2)
{

    int flag = 0, char_index = 0, counter = 0;
    if(_source2.length() < _source1.length()){
        return false;
    }
    char[] _stringchar = _source1.toCharArray();
    char[] _tocheck = _source2.toCharArray();
    for(char character : _stringchar)
    {
        char_index = character - 'a';
        if((flag & (1 << char_index)) == 0)
            flag |= (1 << char_index);
    }

    for(char toCheckcChar : _tocheck)
    {
        char_index = toCheckcChar - 'a';

        if((flag & (1 << char_index)) > 0)
            counter++;
        else
            counter = 0;

        if(counter == _source1.length())
            return true;

    }

    return false;
}
于 2014-05-12T17:02:27.140 回答
0

我想下面的解决方案很O(n)复杂,如果有人不同,请告诉我。

import java.util.HashMap;
import java.util.Scanner;


public class Anagrams {

    static boolean isAnagram(String word1, String word2)
    {
        if(word1.length() != word2.length()) {
            return false;
        }
        int flag=0;
        HashMap<Character,Integer> table = new HashMap<Character,Integer>();
        for(int i=0; i< word1.length();i++) {
            table.put(word1.charAt(i),1);
        }

        for(int i=0; i< word2.length();i++) {
            if(table.containsKey(word2.charAt(i))) {
                continue;
            } else {
                flag=1;
                break;
            }   
        }
        return flag == 0;
    }

    public static void main(String[] args) {
        System.out.println("Enter your string");
        Scanner sc= new Scanner(System.in);
        String word1= sc.nextLine();
        String word2=sc.nextLine();

         boolean result = isAnagram(word1,word2);
         if(result) {
             System.out.println("The words are Anagrams");
         } else{
             System.out.println("The words are not Anagrams");   
         }
    }
}
于 2013-12-20T00:33:45.530 回答
0

只见 newStr=s2.replace(delStr,"");

您在这里所做的替换 s2 中的 char 并分配回 newStr,意味着您没有更改 s2 中的任何内容。只需将此代码替换为以下代码即可

newStr=newStr.replace(delStr,"");

于 2015-04-21T17:27:33.383 回答
0

有一次我做了一个关于字谜的求职面试测试。我将它上传到我的 github 帐户。java 代码检查文本文件(多行)是否是字谜诗或字谜文本。

https://github.com/javocsoft/anagram_poem_checker

希望能帮助到你!

再见。

于 2015-01-01T20:57:58.273 回答
0

这是另一个建议,没有初始化 int[256] 而是 int[26] 用于英文字母。

public static void main(String[] args) {
    System.out.println(isAnagram("restful", "fluster"));
}

static boolean isAnagram(String s1, String s2) {
    if (s1.length() != s2.length()) {
        return false;
    }
    int[] countArray = new int[26];
    for (int i = 0; i < s1.length(); i++) {
        countArray[getIndex(i, s1)]++;
        countArray[getIndex(i, s2)]--;
    }
    for (int i = 0; i < countArray.length; i++) {
        if (countArray[i] != 0) {
            return false;
        }
    }
    return true;
}

public static int getIndex(int position, String value) {
    return value.charAt(position) - 'a';
}

最佳乔治·索普里迪斯

于 2018-12-30T15:39:47.420 回答
0
    String str1="Mother In Law";
    String str2="Hitler Woman";
    char[] anag1=str1.replaceAll("\\s", "").toLowerCase().toCharArray();
    char[] anag2=str2.replaceAll("\\s", "").toLowerCase().toCharArray();
    Arrays.sort(anag1);
    Arrays.sort(anag2);
    System.out.println(Arrays.equals(anag1, anag2)? "words are anagrams":"words are not anagrams");
于 2017-05-12T16:36:06.993 回答
0

这是我从您的角度来看的解决方案

private static boolean isAnagram(String s1, String s2){
    int count = 0;
    boolean flag = false;

    if(s1.length() != s2.length()){
        return false;
    }
    //checks whether both word's letters are the same
    for (int i = 0; i < s1.length(); i++){
        for (int j = 0; j < s2.length(); j++){
            if(s1.charAt(i) == s2.charAt(j)){
                count++;
                break;
            }
        }
    }
    //if count equals to one of the Strings length then it is an anagram
    if(count == s2.length() ){
        flag = true;
    }
    return flag;
}
于 2017-03-19T22:10:05.460 回答
0

这是我为使用数组而不是 HashMap 而编写的 Java 实现。这节省了空间,而且数组非常快。

public static boolean anagram(String s, String t) { 
        if (s.length() != t.length()) return false;

        int[] arr = new int[123];
        for (char c : s.toCharArray())
            arr[c]++;
        for (char c : t.toCharArray())
            arr[c]--;
        for (int i : arr)
            if (i != 0)
                return false;
        return true;
    }
于 2016-07-08T22:08:31.310 回答
0

我认为这适用于复杂度 O(2n)

public static boolean isAnagram(String str1, String str2){
    if(str1.length() != str2.length()){ return false;}
    int[] buffer = new int[256];
    for(char ch : str1.toCharArray()){
        buffer[ch]++;
    }
    for(char ch : str2.toCharArray()){
        if(buffer[ch]==0) return false;
        buffer[ch] = (buffer[ch] > 0)?(buffer[ch] - 1 ): -1 ;   
    }
    return true;
}
于 2016-01-22T09:46:12.093 回答
0
import java.util.Scanner;

public class JavaProgram
{
    public static void main(String[] input)
    {
        String str1, str2;
        int len, len1, len2, i, j, found=0, not_found=0;
        Scanner scan = new Scanner(System.in);

        System.out.print("Enter First String : ");
        str1 = scan.nextLine();
        System.out.print("Enter Second String : ");
        str2 = scan.nextLine();

        len1 = str1.length();
        len2 = str2.length();

        if(len1 == len2)
        {
            len = len1;
            for(i=0; i<len; i++)
            {
                found = 0;
                for(j=0; j<len; j++)
                {
                    if(str1.charAt(i) == str2.charAt(j))
                    {
                        found = 1;
                        break;
                    }
                }
                if(found == 0)
                {
                    not_found = 1;
                    break;
                }
            }
            if(not_found == 1)
            {
                System.out.print("Strings are not Anagram to Each Other..!!");
            }
            else
            {
                System.out.print("Strings are Anagram");
            }
        }
        else
        {
            System.out.print("Both Strings Must have the same number of Character to be an Anagram");
        }
    }
}
于 2016-10-15T17:42:25.097 回答
0
public class Anagram {
    public boolean isAnagram(
            String left, 
            String right) {
        if (left.length() == right.length()) {
            Map<Character, Integer> map = new HashMap<>();
            char[] a = left.toCharArray(), b = right.toCharArray();
            for (int i = 0; i < a.length; i++) {
                accumulate(map, a[i]);
                accumulate(map, b[i]);
            }
            for (char c : map.keySet()) {
                if (map.get(c) > 0) {
                    return false;
                }
            }
            return true;
        } else {
            return false;
        }
    }

    private void accumulate(
            Map<Character, Integer> map, 
            char key) {
        if (map.containsKey(key)) {
            map.put(key, Math.abs(map.get(key) - 1));
        } else {
            map.put(key, 1);
        }
    }
}
于 2017-02-03T21:53:21.807 回答
0

我花了一些时间来实际写下逻辑并编写代码来检查两个字符串是否是字谜。当然是在上面的答案的帮助下!XD

public static void main(String[] args) {

    Map<Character, Integer> char_map = new HashMap<Character, Integer>();
    Map<Character, Integer> empty_map = new HashMap<Character, Integer>();
    String a = "HelloP";
    String b = "HePlol";

    if (a.length() != b.length()) {
        System.out.println("false");
        System.exit(0);
    }

    for (char c : a.toLowerCase().toCharArray()) {
        empty_map.put(c, 0);
        if (char_map.containsKey(c))
            char_map.put(c, 1 + char_map.get(c));
        else
            char_map.put(c, 1);
    }

    for (char c : b.toLowerCase().toCharArray())
        if (char_map.containsKey(c))
            char_map.put(c, char_map.get(c) - 1);

    System.out.println(char_map.equals(empty_map));
}
于 2015-10-09T20:26:37.460 回答
0

一种针对性能进行优化的解决方案。

与其他解决方案有何不同:

  • 只有在绝对最坏的情况下,它才会迭代一次text1 和一次 text2
  • 快速失败:在 text1 中遇到不属于 text2 的字符时立即返回 false
  • 将直方图存储为int[],这比 HashMaps 或类似的要快得多
  • 可以处理任何字符的字符串(甚至是表情符号

示例代码:

public static boolean check(String text1, String text2) {
    requireNonNull(text1, "text1 must not be null");
    requireNonNull(text2, "text2 must not be null");
    if (text1 == text2) return true;

    var text1Chars = text1.toCharArray();
    var text2Chars = text2.toCharArray();
    if (text1Chars.length != text2Chars.length) return false;

    var text2Counts = new int[Character.MAX_CODE_POINT];
    var text2Index = 0;

    loopThroughText1:
    for (char charOfText1 : text1Chars) {
        if (text2Counts[charOfText1] > 0) {
            text2Counts[charOfText1]--;
        } else {
            while (text2Index < text2Chars.length) {
                var charOfText2 = text2Chars[text2Index++];
                if (charOfText1 == charOfText2) {
                    continue loopThroughText1;
                }
                text2Counts[charOfText2]++;
            }
            return false;
        }
    }
    return text2Index >= text2Chars.length;
}

对应的测试方法:

@ParameterizedTest
@CsvSource({
        "a,a,true",
        "a,b,false",
        "aa,a,false",
        "a,aa,false",
        "aa,aa,true",
        "vhjsd682ahjsvdi7861rUZVFD/Ias6srf871r23,vhjsd682ahjsvdi7861rUZVFD/Ias6srf871r23,true",
        "A,a,false",
        ",,true",
        ",,false",
})
public void check(String text1, String text2, boolean expected) {
    assertEquals(AnagramChecker.check(text1, text2), expected);
}
于 2021-11-08T13:42:34.893 回答
0
  1. 如果相等,比较两个字符串的长度
  2. 将两个字符串都转换为小写,以便进行有效比较
  3. 循环检查 String1 是否包含 String2 中的字符。
  4. 将计数器设置为其中一个字符串的长度,并在匹配时减少 -1

    public boolean isAnagram(String s1, String s2) {
    
    if(s1.length() != s2.length()) {
        return false;
    }
    
    int counter= s1.length();
    s1 = s1.toLowerCase();
    s2= s2.toLowerCase();
    
    for (int i=0; i<s1.length();i++ ) {
    
            if (s2.contains(s1.charAt(i)+"")) {
    
                counter--;              
        }
    }
    
    if (counter<=0) {
    
        return true;
    }
    return false;
    }
    
于 2020-01-21T18:53:22.410 回答
0

使用 Java 流,这可以在 5 行代码中简化(https://github.com/vspiliop/java-puzzles/blob/master/src/gy/etiolo/puzzles/streams/Anagrams.java):

/**
 * Are two strings anagrams.
 */
public class Anagrams {
  public static void main(String ... args) {
    String word1 = "abcdefg";
    String word2 = "gfedabc";

    System.out.println("Are they anagrams: " + isAnagram(word1, word2));
  }

  private static boolean isAnagram(String word1, String word2) {
    int [] mask = new int[26];
    Arrays.fill(mask, 0);
    word1.toLowerCase().chars().forEach(c -> mask['z' - c]++);
    word2.toLowerCase().chars().forEach(c -> mask['z' - c]--);
    return Arrays.stream(mask).sum() == 0;
  }
}

在此处查看 ascii 表:http ://www.asciitable.com/

于 2020-04-10T11:38:21.870 回答
0
public class SampleAnagram {

    public static void main(String ...s) {


        String s1 = "work";
        String s2="kwro";

        System.out.println(s1.charAt(0));

        int s1L = s1.length();
        int s2L = s2.length();

        int totalCount = 0;

            for(int i=0;i<s1L;i++) {

                for(int j=0;j<s2L;j++) {

                if(s1.charAt(i)==(s2.charAt(j))) {

                    totalCount = totalCount+1;
                }
            }
        }

            System.out.println(totalCount);


            if(s1.length()==totalCount && s2.length()==totalCount) {

                System.out.println("given the input as anagram");
            }

    }



}
于 2018-12-13T03:07:16.480 回答
0
public static boolean isAnagram(String s1, String s2) {
    if (s1.length() != s2.length()) {
        return false;
    }
    Map<Character, Integer> frequencies = new HashMap<>();
    for (int i = 0; i < s1.length(); i++) {
        if (frequencies.containsKey(s1.charAt(i))) {
            frequencies.put(s1.charAt(i), frequencies.get(s1.charAt(i)) + 1);
        } else {
            frequencies.put(s1.charAt(i), 1);
        }
    }
    for (int i = 0; i < s2.length(); i++) {
        if (frequencies.containsKey(s2.charAt(i))) {
            int frequency = frequencies.get(s2.charAt(i));
            if (--frequency == 0) {
                frequencies.remove(s2.charAt(i));
            } else {
                frequencies.put(s2.charAt(i), frequencies.get(s2.charAt(i)) - 1);
            }
        }
    }
    return frequencies.isEmpty();
}
于 2019-03-22T20:09:03.693 回答
0
public static boolean isAnagram(String s1, String s2) {
    boolean aux = true;
    if (s1.length() != s2.length()){
        aux = false;
    }else{ 
        for (int i = 0; i < s1.length(); i++)
            if(s2.toUpperCase().indexOf(s1.toUpperCase().substring(i, i+1)) == -1) aux = false;
    }
    return aux;
}
于 2018-06-21T17:06:38.713 回答
-1
public boolean isAnagram(String a, String b) {

  boolean result = false;

  final String one = a.replaceAll("[\\s+\\W+]", "").toLowerCase();

  final String two = b.replaceAll("[\\s+\\W+]", "").toLowerCase();

  if (one.length() == two.length()) {

      final char[] oneArray =  one.toCharArray();

      final char[] twoArray =  two.toCharArray(); 

      Arrays.sort(oneArray);

      Arrays.sort(twoArray);

      result = Arrays.equals(oneArray, twoArray);

    }

  return result; 

}
于 2013-07-12T16:43:15.253 回答
-2
import java.util.*;
class Anagrams 
{
    public static void main(String[] args) 
    {
        System.out.println("Enter the two words");
        Scanner scan = new Scanner(System.in);
        String word1 = scan.next();
        String word2=scan.next();

        StringBuilder sb1= new StringBuilder(word1);
        StringBuilder sb2= new StringBuilder(word2);
        int count=0;
        System.out.println("length ! "+sb1.length());
        System.out.println("Length ! "+sb2.length());
        if(sb1.length()==sb2.length()){
            for(int i=0;i<sb1.length();i++){
                for(int k=0;k<sb2.length();k++){
                    if(sb1.charAt(i)==sb2.charAt(k)){
                        sb2.deleteCharAt(k);
                        count++;
                        System.out.println("Count is "+count);
                        break;
                    }
                }
            }

            if(count==sb1.length()){

                System.out.println("Anagrams!");
            }
            else{
                System.out.println("Not Anagrams");
            }
        }
        else{
            System.out.println("Not equal in length");
        }
    }
}
于 2013-04-25T13:06:14.737 回答