0

say I have String x= "algorithm" , and Stringy= "mgth"

String x contains all the letters in String y, I can split String y into a list of letters, and loop through this list to see if String x contains the letter y[index] ,, but I wonder If there's a more efficient way

Edit:

in kotlin there's a simple intersect function,, for example:

val x="algorithm".toList()
val y="mgth".toList()
val interesct=x.intersect(y) //returns a Set of matching chars

if (y.size == interesct.size){
    println("match")
}
0

3 Answers 3

1

Regexp for the rescue:

    String pattern = "mgth".chars()
            .mapToObj(ch -> "(?=.*" + (char) ch + ")")
            .collect(Collectors.joining());

    // ".*(?=.*m)(?=.*g)(?=.*t)(?=.*h).*"
    boolean matches = Pattern.compile(".*"+pattern+".*")
            .matcher("algorithm")
            .matches();

    System.out.println(matches);

This will match only if "algorithm" contains all characters in generated pattern from target string.

EDIT

Also, you can sort both strings, and perform comparison only in interval of [min("mgth"), max("mgth")] char values.

Sign up to request clarification or add additional context in comments.

Comments

1

There is a more efficient way by using a Set.

String x = "algorithm";
String y = "mgth";
Set<Character> set = new HashSet<>();

for(char c: y.toCharArray())
   set.add(c);
for(char c: x.toCharArray())
   set.remove(c);

if(set.size() == 0) 
    System.out.println("X contains Y");
else 
    System.out.println("X does not contain Y");

What the above code does is add the characters in the smaller String to the set. Then, it removes each of the characters in the larger String.

If there are any leftover characters in the Set, then that means that the smaller String contained a letter that was not in the larger String.

2 Comments

Be careful of using String instead of character there - you don't actually want a set of String. You could also do Set<Character> ySet = new HashSet<>(y.toCharArray()); Set<Character> intersection = (new HashSet<>(set)).retainAll(ySet); if (intersection.size <> ySet.size())
Actually, the toCharArray thing won't work. It'll produce List<char[]> Probably should use something more like y.chars().mapToObj(c->(char) c).collect(Collectors.toList());
1

Try this one

@Test
public void similarity() {
  String x = "algorithm";
  String y = "mgth";
  final boolean ohYes =
      y.chars().filter(yc -> x.chars().anyMatch(xc -> yc == xc)).count() == y.length();
  Assert.assertTrue(ohYes);
}

2 Comments

this will return true if at least one character in X is equal. The question is about all Y characters equation.
Nope, all characters, see the y.lenght() equality.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.