简体   繁体   English

分割字符串并检查它们是否彼此相似

[英]To split a string and to check if they are anagram to each other

I am trying to solve this question: https://www.hackerrank.com/challenges/anagram 我正在尝试解决此问题: https : //www.hackerrank.com/challenges/anagram

Here's my code: 这是我的代码:

import java.util.*;

public class Anagram {

    public static void main(String[] args)
    {
        Scanner reader = new Scanner(System.in);
        int t = reader.nextInt();

        while((t--) > 0)
        {    
            String input = reader.nextLine();

            if((input.length()) % 2 == 1)
                System.out.println(-1);
            else
            {
                int x = input.length();
                int q = (int)(Math.floor((x / 2)));

                String input1 = input.substring(0, q);
                String input2 = input.substring(q, x);

                int [] count2 = new int[26];
                for(int i = 0; i < input2.length(); i++)
                {
                    char ch2 = input2.charAt(i);
                    count2[ch2 - 'a']++;
                }

                // int [] count1 = new int[26];
                for(int i = 0; i < input1.length(); i++)
                {
                    char ch1 = input1.charAt(i);
                    if(count2[i] > 0)
                        count2[ch1 - 'a']--;
                }

                int count = 0;
                for(int j = 0; j < 26; j++)
                {
                    count = count + Math.abs(count2[j]);
                }

                System.out.println(count);
            } 
        }
    }
} 

Sample Input 样本输入

6
aaabbb
ab
abc
mnop
xyyx
xaxbbbxx

Expected Output 预期产量

3
1
-1
2
0
1

My output 我的输出

0
4
1
-1
2
2

Can anyone please tell me where it went wrong? 谁能告诉我哪里出了问题? I couldn't find the error... 我找不到错误...

You can use this to check if two strings are palindromes: 您可以使用它来检查两个字符串是否为回文式:

String original = "something";
String reverse = new StringBuilder(original).reverse().toString();

boolean anagram = original.equals(reverse);

Your first output always comes 0, because of this line: 由于以下这一行,您的第一个输出始终为0:

int t = reader.nextInt();

followed by reader.nextLine(); 其次是reader.nextLine(); . Check this post for more details on that . 有关更多详细信息,请查看这篇文章 For quick fix, change that line to: 为了快速修复,将该行更改为:

int t = Integer.parseInt(reader.nextLine());

Now, let's start with the below two statements: 现在,让我们从以下两个语句开始:

int x = input.length();
int q = (int)(Math.floor((x/2)));

No need to do a Math.floor there. 无需在此处执行Math.floor x/2 is an integer division, and will give you integer result only. x/2是整数除法,只会给您整数结果。

Moving to the 2nd for loop. 移动到第二for循环。 You used the following condition: 您使用了以下条件:

if(count2[i]>0)
    count2[ch1-'a']--;

Notice the mistake there in condition? 注意条件错误吗? It should be count2[ch1 - 'a'] > 0 . 它应该是count2[ch1 - 'a'] > 0 And also, you will miss the case where that count is not greater than 0, in which case you would have to do a ++ . 而且,您将错过该计数不大于0的情况,在这种情况下,您将必须执行++ BTW, since you're anyways doing a Math.abs() , you don't need the condition. 顺便说一句,由于您Math.abs()在执行Math.abs() ,因此您不需要该条件。 Just do a -- : 只是做一个--

for( int i = 0; i < input1.length(); i++ ) {
    char ch1 = input1.charAt(i);
    count2[ch1-'a']--;
}

BTW, the final result would be count / 2 , and not count , because count contains the total mismatch from input1 to input2 and vice-versa. 顺便说一句,最终结果将是count / 2 ,而不是count ,因为count包含从input1到input2的总不匹配,反之亦然。 But we just have to fix one of them to match the other. 但是我们只需要修复其中一个以匹配另一个即可。 So, just consider half the total mismatch. 因此,只考虑总失配的一半。

As per your question, main logic could be changed to something like below. 根据您的问题,主要逻辑可以更改为如下所示。

Note - I have added only the main logic and excluded the user inputs here. 注-我仅添加了主要逻辑,并在此排除了用户输入。

public static void main(String[] args) {
    String str = "acbacccbaac";
    int len = str.length();
    String str1 = null, str2 = null;
    if(len %2 != 0) {//check for odd length
        str1 = str.substring(0, len/2);
        str2 = str.substring(len/2+1, len);
    }else {//check for even length
        str1 = str.substring(0, len/2);
        str2 = str.substring(len/2, len);
    }
    char[] arr1 = str1.toLowerCase().toCharArray();
    Arrays.sort(arr1);
    char[] arr2 = str2.toLowerCase().toCharArray();
    Arrays.sort(arr2);
    if(Arrays.equals(arr1, arr2))
        System.out.println("Yes");
    else
        System.out.println("No");
}

I implemented this way for the same problem in my HackerRank profile, and works great. 我在HackerRank个人资料中针对相同问题实施了这种方法,效果很好。

This is my solution to the prob and it works! 这是我对问题的解决方案,并且有效!

static int anagram(String s) {
        String a = "";
        String b = "";
        if (s.length() % 2 == 0) {
            a = s.substring(0, s.length() / 2);
            b = s.substring((s.length() / 2), s.length());
        }

        if (s.length() % 2 != 0) {
            a = s.substring(0, s.length() / 2);
            b = s.substring((s.length() / 2), s.length());
        }
        if (a.length() == b.length()) {
            char[] aArray = a.toCharArray();
            char[] bArray = b.toCharArray();
            HashMap<Character, Integer> aMap = new HashMap<Character, Integer>();
            HashMap<Character, Integer> bMap = new HashMap<Character, Integer>();
            for (char c : aArray) { // prepare a Hashmap of <char>,<count> for first string
                if (aMap.containsKey(c)) {
                    aMap.put(c, aMap.get(c) + 1);
                } else {
                    aMap.put(c, 1);
                }
            }

            for (char c : bArray) {// prepare a Hashmap of <char>,<count> for second string
                if (bMap.containsKey(c)) {
                    bMap.put(c, bMap.get(c) + 1);
                } else {
                    bMap.put(c, 1);
                }
            }
            int change = 0;
            for (Map.Entry<Character, Integer> entry : bMap.entrySet()) {
                System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                if (!aMap.containsKey(entry.getKey())) {
                    change += entry.getValue();
                } else {
                    if (entry.getValue() > aMap.get(entry.getKey())) {
                        change += entry.getValue() - aMap.get(entry.getKey());
                    } else {
                        //change += entry.getValue();
                    }
                }
            }
            return change;
        } else {
            return -1;
        }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM