Java > Warmup-2 > stringMatch (CodingBat Solution)

Problem:

Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. So "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.

stringMatch("xxcaazz", "xxbaaz") → 3
stringMatch("abc", "abc") → 2
stringMatch("abc", "axc") → 0


Solution:

public int stringMatch(String a, String b) {
  int len = Math.min(a.length(), b.length());
  int count = 0;
  
  for (int i = 0; i < len-1; i++){
    String aSub = a.substring(i, i+2);
    String bSub = b.substring(i, i+2);
    if (aSub.equals(bSub))
      count++;  
  }
  return count;
}


1 comment :

  1. int min, counter=0;
    if (a.length()>b.length()) min=b.length();
    else min=a.length();
    for (int i=0;i<min-1;i++){
    if (a.substring(i,i+2).equals(b.substring(i,i+2))) {
    counter++;
    }
    }
    return counter;

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact