Solved

substring count challenge

Posted on 2014-11-05
26
172 Views
Last Modified: 2014-11-16
Hi,

I am working on below challenge
http://codingbat.com/prob/p198640

i wrote code as below
public class Test27 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int numberCount=stringMatch("abc","abc");
		System.out.println("is-->"+numberCount);
	}
	
	
	public static int stringMatch(String a, String b) {
		int count=0;
		for(int i=0;i<=a.length()-1;i++){
		if(a.substring(i,i+1)==a.substring(i,i+1))
		count++;
		}
		return count;
		  
		}

}

Open in new window


I have many test cases failing as below

Expected      Run            
stringMatch("xxcaazz", "xxbaaz") → 3      0      X         
stringMatch("abc", "abc") → 2      0      X         
stringMatch("abc", "axc") → 0      0      OK         
stringMatch("hello", "he") → 1      0      X         
stringMatch("he", "hello") → 1      0      X         
stringMatch("h", "hello") → 0      1      X         
stringMatch("", "hello") → 0      0      OK         
stringMatch("aabbccdd", "abbbxxd") → 1      0      X         
stringMatch("aaxxaaxx", "iaxxai") → 3      0      X         
stringMatch("iaxxai", "aaxxaaxx") → 3      0      X         


How to fix and improve my code. Please advise
0
Comment
Question by:gudii9
  • 11
  • 7
  • 4
  • +1
26 Comments
 
LVL 27

Assisted Solution

by:rrz
rrz earned 167 total points
ID: 40425075
1)You must use String's equals method to compare the Strings. Don't use == to compare them.
2)You are comparing a substring from "a" with the same thing. You need to compare a substring from "a" to a substring from "b".    
3)You are comparing a substring length of 1.  But the challenge asks you compare substring length of 2.
4)You don't consider different lengths of input Strings. You could use Math.min method to find the shorter String length.
0
 
LVL 27

Expert Comment

by:dpearson
ID: 40425104
There are several problems with your code.

Compare to this code and see if you can spot  the differences?

Doug

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

Open in new window

0
 
LVL 27

Expert Comment

by:dpearson
ID: 40425107
Oops - I see rrz posted largely the same thing (as text).  Apologies - my browser didn't update in time.

DOug
0
Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

 
LVL 27

Expert Comment

by:rrz
ID: 40425123
No problem, Doug.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40431866
public int stringMatch(String a, String b) {
int count=0;
		for(int i=0;i<=a.length()-1&&i<=b.length()-1;i++){
		if(a.substring(i,i+2).equals(b.substring(i,i+2)))
		count++;
		}
		return count;
  
}

Open in new window


can I see both a and b lenth with && in the for loop as above. I still do not pass tests as above?
when to use == and when to use .equals? Please advise
0
 
LVL 7

Author Comment

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


	

Open in new window


when i wrote as above i am getting index out of bound on many test cases.

Expected      Run            
stringMatch("xxcaazz", "xxbaaz") → 3      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 7 (line number:4)      X         
stringMatch("abc", "abc") → 2      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 4 (line number:4)      X         
stringMatch("abc", "axc") → 0      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 4 (line number:4)      X         
stringMatch("hello", "he") → 1      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 3 (line number:4)      X         
stringMatch("he", "hello") → 1      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 3 (line number:4)      X         
stringMatch("h", "hello") → 0      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 2 (line number:4)      X         
stringMatch("", "hello") → 0      0      OK         
stringMatch("aabbccdd", "abbbxxd") → 1      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 8 (line number:4)      X         
stringMatch("aaxxaaxx", "iaxxai") → 3      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 7 (line number:4)      X         
stringMatch("iaxxai", "aaxxaaxx") → 3      Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: 7 (line number:4)      X      

To me the above code is same as the code you posted. please advise

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

Open in new window


your code as above is passing all tests
0
 
LVL 84

Expert Comment

by:ozo
ID: 40431879
Do you understand the difference between < and <= ?
0
 
LVL 7

Author Comment

by:gudii9
ID: 40431889
yes i see the difference. why we should use .equals but not ==.

Till now i was using == for characters i believe. please advise
0
 
LVL 84

Expert Comment

by:ozo
ID: 40431933
I did not say anything about ==
Neither of the examples in your http:#a40431871 comment use ==
0
 
LVL 7

Author Comment

by:gudii9
ID: 40433014
Do you understand the difference between < and <=

I understand the difference.

if i say i<4 it only looks till 3 i.e 0,1,2,3 not 4
if i say i<=4 then it look till 4 including 4 i.e 0,1,2,3,4
0
 
LVL 7

Author Comment

by:gudii9
ID: 40433033
I found one link which explained me the difference between == and equals clearly
http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/
0
 
LVL 7

Author Comment

by:gudii9
ID: 40433089
for(int i=0;i<=len-1;i++){

Open in new window


My code i should not have said as above.

for(int i=0;i<len-1;i++){

Open in new window

Above one is correct which does not go beyond the limit
0
 
LVL 27

Expert Comment

by:rrz
ID: 40436640
Till now i was using == for characters

Yes, we use that shortcut.  The long way is to use the equals method in the Character class. Look at
https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#equals(java.lang.Object) 
and run
public class Test {
	public static void main(String[] args) {
        char aChar = 'a';
        char bChar = 'b';
        Character aCharacter = new Character(aChar);
		if(aChar + 1 == bChar)System.out.println("Yes, aChar + 1 equals bChar");
        if(aCharacter.equals(aCharacter))System.out.println("Sure it does");        
	}
}          

Open in new window

The output is
>java Test
Yes, aChar + 1 equals bChar
Sure it does
You can see that using  == with char really is comparing int values. Look at
http://www.scism.lsbu.ac.uk/jfl/Appa/appa4.html   
to see values. You see value of 'a' is 97 and value of 'b' is 98.
when to use == and when to use .equals?
You can read at
http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/   
and  
http://javarevisited.blogspot.com/2012/12/difference-between-equals-method-and-equality-operator-java.html   
       
You should use == to compare objects(refer to the same place in memory) or primitives(int value for example).
You should use String's equal method to compare the contents of each String.

If you look at API
https://docs.oracle.com/javase/7/docs/api/index-files/index-5.html   
You will see many equals methods. Most classes have a equals method that override the equals method of the Objects  class. See
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)   
where it says
The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).
But, the equals method in subclasses(like the String class) override the Object class equals method and compare contents or attributes that make sense for that class.
0
 
LVL 27

Expert Comment

by:dpearson
ID: 40436715
The general rule is:

Use == for primitives (double, int, char, boolean etc.)   <-- these types all start with a lowercase later
Use equals for objects (String, Object, Integer, etc.)      <-- these types all start with an uppercase later

If you call a method - check what it returns.

String x ;
x.substring(1,2)   <-- returns String so use equals to test
x.substring(1,2).equals("hello") ;

x.charAt(3)   <-- returns char so use ==
x.chatAt(3) == 'x' ;

Doug
0
 
LVL 27

Expert Comment

by:rrz
ID: 40437598
Also, from one of the links I posted.
In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40437814
>java Test
Yes, aChar + 1 equals bChar
Sure it does
we  got above highlighted output because 97+1=98 right(as 98 is the ordinal number of the character in the range 0 to 255 for 'b Lower case B' as attached from below link)?
http://www.scism.lsbu.ac.uk/jfl/Appa/appa4.html
so for char it is ideally better to use == as it is primitive. But practically i can use either == or equals  which does same thing functionally right. (== compares ordinal number of the character of aChar and bChar and .equals checks the content hence   if(aCharacter.equals(aCharacter))System.out.println("Sure it does"); results Sure it does. Ofcourse downside of using equals with char primitive is i have to cast primitive to object Character type as below  before hand right?(so better to use == itself to make coding easy while using char)
  Character aCharacter = new Character(aChar);
0
 
LVL 7

Author Comment

by:gudii9
ID: 40437847
 String letter = str.substring(i,i+1) ;
  if(i == 0 || i == str.length()-1 || !letter.equals("x"))
    sb.append(letter) ;

I see in above example x is character but they are using as string (within " " as "x", not they are not converting char to Character like Character xCharacter=new Character(x)) then using .equals similar to how they use .equals on Objects and String.
Which seems bit odd to me.
Please advise
0
 
LVL 27

Expert Comment

by:rrz
ID: 40437933
we  got above highlighted output because 97+1=98 right(as 98 is the ordinal number of the character in the range 0 to 255 for 'b Lower case B' as attached from below link)?
Yes  
so for char it is ideally better to use == as it is primitive.
It is just easier.
i have to cast primitive to object Character type as below  before hand right?
That is not casting. We are using the constructor to create a new object.  It is known as boxing. You should also realize that there is a thing called autoboxing. See    
http://javarevisited.blogspot.com/2012/07/auto-boxing-and-unboxing-in-java-be.html       
So, we can also add the following line to my code.
if(aCharacter.equals(aChar))System.out.println("Sure it does, because of autoboxing!");

Open in new window

0
 
LVL 27

Expert Comment

by:rrz
ID: 40438004
I see in above example x is character
No. You are comparing a String to a String. Just as Doug pointed out, the substring method returns a String.  The String class implements the CharSequence interface. See
https://docs.oracle.com/javase/7/docs/api/java/lang/CharSequence.html   
So, String  is a readable sequence of char values.  As Doug posted, some of String's method return char and some return String.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40438142
!letter.equals("x")

i mistakenly thought letter is a 'char'.

As Doug posted, some of String's method return char and some return String.

I wonder where is the corresponding link. which string methods return char?
i see only charValue() method returns char and valueOf returns Character in below API as below

https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#equals(java.lang.Object)

static Character      valueOf(char c)
Returns a Character instance representing the specified char value.
0
 
LVL 27

Expert Comment

by:rrz
ID: 40438594
which string methods return char?
Sorry, I posted without looking at
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html 
I only see the method charAt and the method toCharArray which returns a char array.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40438652
x.substring(1,2).equals("hello") ;

do we need to say above statement as below
(x.substring(1,2)).equals("hello") ;
please advise
0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 167 total points
ID: 40438928
No, because you can replace
(x.substring(1,2)).equals("hello")
with
false

If you had said
(x.substring(1,2)).equals("h")
then that could be replaced with
x.charAt(1)=='h'
0
 
LVL 7

Author Comment

by:gudii9
ID: 40444058
No, because you can replace
(x.substring(1,2)).equals("hello")
with
false

i was not clear on above. can you please elaborate


I was clear on below

If you had said
(x.substring(1,2)).equals("h")
then that could be replaced with
x.charAt(1)=='h'
0
 
LVL 84

Expert Comment

by:ozo
ID: 40444180
A string of length 1 never equals a string of length 5.
0
 
LVL 27

Accepted Solution

by:
dpearson earned 166 total points
ID: 40445987
x.substring(1,2).equals("hello") ;

do we need to say above statement as below
(x.substring(1,2)).equals("hello") ;
please advise

Yes - you can write the original expression
   x.substring(1,2).equals("hello")
as
   (x.substring(1,2)).equals("hello") ;

if that makes it clearer that the "x.substring(1,2)" part executes first and returns a value, which we then use "equals" on.

You can also write it as:
   String sub = x.substring(1,2) ;
   sub.equals("hello") ;

if that helps make it clearer.  They'll all produce the same results.

Doug
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Eclipse with gitlab 1 81
Problem to picture file 20 65
Not seen Link button 5 58
throw exception 21 58
Navigation is an important part of web design from a usability perspective. But it is often a pain when it comes to a developer’s perspective. By navigation, it often means menuing. This is less theory and more practical of how to get a specific gro…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question