Skip to main content
Code Review

Return to Revisions

2 of 2
Converted into a routine code review question, removing request for general career/education advice
200_success
  • 145.6k
  • 22
  • 190
  • 479

Counting length-2 substrings that are common to two strings at the same offset

I am working through the CodingBat exercises for Java. I just completed this one, an exercise that requests the comparison of substrings of two strings:

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

Here is my method (which does work):

public int stringMatch(String a, String b) {
 int count = 0;
 String sub2 = "";
 String arrayA[] = new String[a.length()];
 String arrayB[] = new String[b.length()];
 for (int i = 0; i < a.length()-1; i++) {
 sub2 = a.substring(i, i+2);
 arrayA[i] = sub2; 
 }
 
 for (int i = 0; i < b.length()-1; i++) {
 sub2 = b.substring(i, i+2);
 arrayB[i] = sub2; 
 }
 for (int j = 0; j < arrayA.length-1; j++) {
 if (j >= b.length())
 break;
 
 if (arrayA[j].equals(arrayB[j]))
 count++;
 }
 return count;
}

And here is the answer on the site:

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)) { // Use .equals() with strings
 count++;
 }
 }
 return count;
}

I feel that my code is longer and messy and drawn out compared to other people's. As a beginner programmer, how should I improve it?

alanbuchanan
  • 1.3k
  • 4
  • 20
  • 31
lang-java

AltStyle によって変換されたページ (->オリジナル) /