Java > Warmup-2 > last2 (CodingBat Solution)

Problem:

Given a string, return the count of the number of times that a substring length 2 appears in the string and also as the last 2 chars of the string, so "hixxxhi" yields 1 (we won't count the end substring).

last2("hixxhi") → 1
last2("xaxxaxaxx") → 1
last2("axxxaaxx") → 2


Solution:

public int last2(String str) {
  if (str.length() < 2) return 0;
 
  String end = str.substring(str.length()-2);

  int count = 0;
  
  for (int i=0; i<str.length()-2; i++) {
    String sub = str.substring(i, i+2);
    if (sub.equals(end)) {
      count++;
    }
  }

  return count;

}


2 comments :

  1. public int last2(String str) {
    int len = str.length();
    int count = 0;

    if(len <= 2){
    return 0;
    }

    for(int i = 0; i < len-2; i++){
    String last = str.substring(len-2);
    if(str.substring(i, i+2).equals(last)){
    count++;
    }
    }
    return count;
    }

    ReplyDelete
  2. public int last2(String str) {
    int count=0;
    int len=str.length();
    for (int i = 0; i <len-2 ; i++) {
    if(str.substring(len-2).compareTo(str.substring(i,i+2))==0){
    count++;
    }


    }
    return count;

    }

    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