搜索char数组以查看char是否匹配

时间:2019-03-28 12:50:13

标签: java

我有两个以两个字符串作为输入的char数组。如果两侧的char具有匹配的char,例如,将char数组转换为字符串char A和B后,它们都至少具有一个H或R,则它将返回true。如果不是,则返回false。

>char[] A = foo(A).toCharArray();
>
>char[] B = foo(B).toCharArray();
>
>System.out.println("String "+A+": "+Arrays.toString(A));
>
>System.out.println("String "+B+": "+Arrays.toString(B));

>String A: [H,  , R,  ]
>
>String B: [R,  , R, R]
>>This will return true

>String A: [ , H,  , R]
>
>String B: [H, H,  , H]
>>This will return true

>String A: [H,  , H,  ]
>
>String B: [R,  , R,  ]
>>This will return false

我很困惑如何制定这样的规则?

5 个答案:

答案 0 :(得分:3)

您可以在此处使用java.util.Set,这将使结果一次迭代。使用java.util.TreeSet可以减少重复次数,从而进一步减少了执行时间

public static void main(String[] args) {
    char[] A = "HR".toCharArray();
    char[] B = "RRR".toCharArray();

    Set<Character> set = new TreeSet<>();
    boolean flag = false;
    for(char c : A) {
        set.add(c);
    }
    for(char c : B) {
        if(set.contains(c)) {
            System.out.println(true);
            flag = true;
            break;
        }
    }
    if(!flag) {
        System.out.println(false);
    }
}

答案 1 :(得分:0)

您可以做的是使用For遍历矩阵,并验证当前项目是“ R”还是“ H”。

boolean returnedValue = false;

for(int i = 0; i< B.length; i++){
  char currentItem = B[i];
  if(currentItem == 'R' || currentItem == 'H'){
    returnedValue = true;
 }
}

return returnedValue;

答案 2 :(得分:0)

使用第一个循环从第一个数组中获取每个元素。

使用第二个循环检查第二个数组中的第一个元素。

检查第一个数组中的当前值是否等于H或R。

如果是,请检查它是否在第二个数组中并返回true。

public static boolean check() {
        String s1 = "ABHEEF", s2 = "RDDFVW";
        char[] arr1 = s1.toCharArray();
        char[] arr2 = s2.toCharArray();

        for (int i = 0; i < arr1.length; i++) {
            for (int j = 0; j < arr2.length; j++) {
                if(arr1[i] == 'H' || arr1[i] == 'R') {
                    if(arr1[i] == arr2[j])
                        return true;
                }

            }
        }
        return false;
    }

答案 3 :(得分:0)

很简单,您只需添加一个嵌套循环

for(int i = 0; i < A.length; i++){
      for(int j = 0; j < B.length; j++){
             if(if B[j] ==A [i]){
                  return true
             }
      }
}

        return false;

答案 4 :(得分:0)

使用Java 1.8,您可以执行以下操作:

//@Momir Sarac
String text1 = "b9H ello";
String text2 ="avn1c fk";
// 32 is for empty space character here, you could do i != ' ' and it would be the same
//turn text1 into intstream each int corresponding to it's char value
//filter empty space ints
//get only distinct out of them
//take a look for any match if some int is contained within text2
boolean result = text1.chars().filter(i->i != 32).distinct().anyMatch(character->text2.contains(String.valueOf(character)) || text2.lastIndexOf(character) != -1);
//print it on screen
System.out.printf("Two texts %s same letter(s).", result ? "have" : "don't have");