Thursday, August 6, 2015

String Matching 1

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.

Input Output
xxcaazz
xxbaaz
3
abc
abc
2
abc
axc
0


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public int stringMatch(String a, String b) {
  int len = (a.length()<=b.length())? a.length() : b.length();
  int count=0;
  for(int x=0;x<len-1;x++){
    if(a.substring(x,x+2).equals(b.substring(x,x+2)))
      count++;
  }
  
  return count;
}

No comments:

Post a Comment