【问题标题】:How to get the count of unmatched character in two strings?如何获取两个字符串中不匹配字符的计数?
【发布时间】:2014-09-20 14:49:03
【问题描述】:

我需要获取两个字符串中不匹配字符的计数。例如

string 1 "hari", string 2 "malar"

现在我需要从两个字符串中删除重复项 ['a' & 'r'] 在两个字符串中都很常见,所以删除它,现在 字符串 1 包含“hi” 字符串 2 包含“mla”.

剩余 count = 5

我试过这段代码,如果重复/重复在相同的字符串中不可用,它工作正常,就像这里的 'a' 在 string 2 中出现两次,所以我的代码不能正常工作。

for (int i = 0; i < first.length; i++) {
                for (int j = 0; j < second.length; j++) {

                    if(first[i] == second[j])
                    {
                        getstrings = new ArrayList<String>();
                        count=count+1;
                        Log.d("Matches", "string char that matched "+ first[i] +"==" + second[j]);                          
                    }
                }
            }
            int tot=(first.length + second.length) - count;

这里的first & second指的是

char[] first  = nameone.toCharArray();
char[] second = nametwo.toCharArray();

此代码对String 1 "sri" string 2 "hari" 工作正常,这里的字符串字符没有重复,所以上面的代码工作正常。帮我解决这个问题?

【问题讨论】:

    标签: java android string


    【解决方案1】:

    这是我的解决方案,

    public static void RemoveMatchedCharsInnStrings(String first,String second)
        {
            for(int i = 0 ;i < first.length() ; i ++)
            {
                char c = first.charAt(i);
                if(second.indexOf(c)!= -1)
                {
                    first = first.replaceAll(""+c, "");
                    second = second.replaceAll(""+c, "");
                }
            }
            System.out.println(first);
            System.out.println(second);
            System.out.println(first.length() + second.length());
    
        }
    

    希望这是您所需要的。如果没有,我会更新我的答案

    【讨论】:

    • 感谢您的回答,如果字符没有在字符串中重复,则此代码可以正常工作。在我的情况下,字符可能会重复,就像我上面所说的 hari malar 这段代码从 string1 中取一个并签入 string2,如果 char 是,则从字符串中删除所有相同的字符,结果是 hi ml
    • 在字符串 1 hari 中只有一个字符可用 a 所以我只需要替换字符串 2 malar 中的一个字符。预期输出为himla,因此总数为5。此处需要更改此代码second.replaceAll(""+c, "");
    • 我解决了此代码中的一些更改非常感谢您的回答和您的时间
    【解决方案2】:

    我看到其他答案并想:必须有一种更具声明性和可组合性的方式来做到这一点! 有,但要长得多……

    public static void main(String[] args) {
        String first = "hari";
        String second = "malar";
        Map<Character, Integer> differences = absoluteDifference(characterCountOf(first), characterCountOf(second));
        System.out.println(sumOfCounts(differences));
    }
    
    public static Map<Character, Integer> characterCountOf(String text) {
        Map<Character, Integer> result = new HashMap<Character, Integer>();
        for (int i=0; i < text.length(); i++) {
            Character c = text.charAt(i);
            result.put(c, result.containsKey(c) ? result.get(c) + 1 : 1);
        }
        return result;
    }
    
    public static <K> Set<K> commonKeys(Map<K, ?> first, Map<K, ?> second) {
        Set<K> result = new HashSet<K>(first.keySet());
        result.addAll(second.keySet());
        return result;
    }
    
    public static <K> Map<K, Integer> absoluteDifference(Map<K, Integer> first, Map<K, Integer> second) {
        Map<K, Integer> result = new HashMap<K, Integer>();
        for (K key: commonKeys(first, second)) {
            Integer firstCount = first.containsKey(key) ? first.get(key) : 0;
            Integer secondCount = second.containsKey(key) ? second.get(key) : 0;
            Integer resultCount = Math.max(firstCount, secondCount) - Math.min(firstCount, secondCount);
            if (resultCount > 0) result.put(key, resultCount);
        }
        return result;
    }
    
    public static Integer sumOfCounts(Map<?, Integer> map) {
        Integer sum = 0;
        for (Integer count: map.values()) {
            sum += count;
        }
        return sum;
    }
    

    这是我更喜欢的解决方案 - 但它要长得多。你已经用 Android 标记了这个问题,所以我没有使用任何 Java 8 功能,这会减少一点(但没有我希望的那么多)。

    但是它会产生有意义的中间结果。但它仍然要长得多:-(

    【讨论】:

      【解决方案3】:

      试试这个代码:

      String first = "hari";
      String second = malar;
      
      String tempFirst = "";
      String tempSecond = "";
      
      int maxSize = ((first.length() > second.length()) ? (first.length()) : (second.length()));
      
      for (int i = 0; i < maxSize; i++) {
          if (i >= second.length()) {
              tempFirst += first.charAt(i);
          } else if (i >= first.length()) {
              tempSecond += second.charAt(i);
          } else if (first.charAt(i) != second.charAt(i)) {
              tempFirst += first.charAt(i);
              tempSecond += second.charAt(i);
          }
      }
      
      first = tempFirst;
      second = tempSecond;
      

      【讨论】:

      • yaa 解决了,感谢您的回答和宝贵的时间。
      【解决方案4】:

      您需要在找到匹配项后立即break;

      public static void main(String[] args) {
              String nameone="hari";
              String nametwo="malar";
              char[] first  = nameone.toCharArray();
              char[] second = nametwo.toCharArray();
              List<String>getstrings=null;
              int count=0;
              for (int i = 0; i < first.length; i++) {
                  for (int j = 0; j < second.length; j++) {
      
                      if(first[i] == second[j])
                      { 
                          getstrings = new ArrayList<String>();
                          count++; 
                          System.out.println("Matches"+ "string char that matched "+ first[i] +"==" + second[j]);  
                          break;
                      } 
                  } 
              } 
              //System.out.println(count);
              int tot=(first.length-count )+ (second.length - count);
      
               System.out.println("Remaining after match from both strings:"+tot);
      
      }
      

      打印:

       Remaining after match from both strings:5
      

      【讨论】:

      • yaa 解决了,感谢您的回答和宝贵的时间。
      【解决方案5】:

      您在这里缺少两件事。

      1. 在 if 条件下,当两个字符匹配时,您需要将 count 增加 2,而不是从两个字符串中删除。
      2. 您需要在 in 条件中添加一个中断,因为您始终匹配第一次出现的字符。

      如下所示在您的代码中进行这两项更改,现在它会按您的预期打印结果。

          for (int i = 0; i < first.length; i++) {
                  for (int j = 0; j < second.length; j++) {
      
                      if(first[i] == second[j])
                      {                       
                          count=count+2;
                          break;
                      }
                  }
              }
              int tot=(first.length + second.length) - count;
              System.out.println("Result = "+tot);
      

      【讨论】:

        【解决方案6】:

        如果字符匹配,您只需要遍历两个字符串增加计数,然后从两个字符的总长度中删除这些计数

        s = 'hackerhappy'\
        t = 'hackerrank'\
        count = 0
        
        
        
        for i in range(len(s)):
            for j in range(len(t)):
               if s[i] == t[j]:
                  count += 2
                  break
        
        char_unmatched = (len(s)+len(t)) - count 
        

        char_unmatched 包含两个字符串中不相等的字符数

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-12-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多