【问题标题】:Find common letters in two Strings (Java) [closed]在两个字符串中查找常用字母(Java)[关闭]
【发布时间】:2019-12-31 12:09:45
【问题描述】:

目标是在两个给定的字符串s1s2 中找到共同的字母。

常用符号串必须至少有两个字母。

输入示例

String s1 = "BAABBBAABBA";
String s2 = "BBBABBBAA";

缩小解决方案的步骤

  1. 步骤:
s1 = BAA**BBBA**ABBA
s2 = **BBBA**BBBABA

len = 4
  1. 步骤:
s1 = BAA____A**BBA**
s2 = ____B**BBA**BA

len = 3

我是一个初学者,在这个案例中挣扎了 4 个小时。 有人可以帮我解决这个问题吗? 很高兴收到 java 中的解决方案。

提前致谢。

【问题讨论】:

  • 4 小时不算什么。卡在某件事上并努力解决它是真正学习的最佳方式。你具体卡在哪里了?你现在用了什么工具?
  • 欢迎来到 SO!这不是解决方案工厂。请阅读How to Ask 并将您的代码尝试发布为minimal reproducible example。所以我们可以引导您朝着正确的方向前进。
  • 正如@Akchene_ye 所建议的,这里有一个可能有用的链接:geeksforgeeks.org/common-characters-n-strings
  • len = 6BA<ABBBAA>BBA 对比 BBB<ABBBAA> 怎么样?

标签: java string algorithm


【解决方案1】:

也许下面的代码可以帮助你。这个想法是从一个字符串创建所有可能的子字符串,以检查子字符串是否包含在另一个字符串中。

import java.util.HashSet;
import java.util.Set;

public class Test {

    public static void main(String[] args) {

        String s1 = "BAABBBAABBA";
        String s2 = "BBBABBBAA";

        Set<String> foundSet = new HashSet<>();

        for (int start = 0; start < s1.length() - 1; ++start) {

            for (int end = start + 2; end <= s1.length(); ++end) {
                String subString = s1.substring(start, end);
                if (s2.contains(subString)) {
                    foundSet.add(subString);
                }
            }
        }

        foundSet.forEach(System.out::println);
    }
}

【讨论】:

    【解决方案2】:
    public class example {
    
        public static void main(String[] args) {
            String string1 = "dabdabdab", string2 = "badbadbad";//In this case the result will be a, a, a, and the count will be 3.
            char a,b;
            int count = 0, y = string1.length(), x = 0;
            char[] charArray;
            for (int i = 0; i < string1.length();i++){
                a = string1.charAt(i);
                b = string2.charAt(i);
                if (a == b){
                    count++;
                }
            }
            charArray = new char[count];//Just for the array to have the size of the exact common elements of the strings.
            for (int i = 0; i < string1.length();i++){
                a = string1.charAt(i);
                b = string2.charAt(i);
                if (a == b){
                    charArray[x] = a;
                    x++;
                }
            }
            //Check if the array has the correct amount of elements.
            for (int i = 0; i < charArray.length; i++){
                System.out.print(charArray[i]);
            }
        }
    }
    

    享受。评论以获得更多建议。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 2014-11-16
      • 1970-01-01
      • 2012-09-11
      • 2016-03-19
      • 2011-01-30
      相关资源
      最近更新 更多