This question already has an answer here:
Why doesn't following java code throw java.lang.StringIndexOutOfBoundsException when there is no element present at index 1?
(1 answer)
Closed 7 years ago.
I am goofing around in CodingBat with Java Strings warm-ups.
The prompt was:
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
My first attempt was:
public int last2(String str) {
String last = str.substring(str.length()-2);
int count = 0;
if (str.length() < 2){
return 0;
}
for (int i = 0; i <str.length()-2; i++){
String sub = str.substring(i,i+2);
if (sub.equals(last)){
count++;
}
}
return count;
}
This code produced the correct output for all tests except when the input string had a length less than 2 (output = Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -1 (line number:3), etc.), meaning the if statement was ignored.
However, simply moving the if statement above the variable declarations in the beginning of the method made the code correctly pass all tests (even strings with length less than two):
public int last2(String str) {
if (str.length() < 2){
return 0;
}
String last = 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(last)){
count++;
}
}
return count;
}
I feel like the variable declarations shouldn't have any impact on the functionality of the if statement... what is keeping my first coding attempt from working?
In your first snippet String last = str.substring(str.length()-2); would throw an exception when str.length < 2, so the if statement didn't get executed at all.
In your second snippet you placed the if statement in the correct location.
Related
The question is: Given two Strings, return the number of the positions where they contain the same substring with a length of 2 .
The code I wrote works but my question is why do I have to add the minus 1 to line 3 which is this part: i<a.length()-1
(I know it has something to do with me using (i,i+2))
public int stringMatch(String a, String b) {
int count = 0;
if (a.length() < b.length()) {
for (int i=0; i<a.length()-1; i++) {
if (a.substring(i,i+2).equals(b.substring(i,i+2))) {
count++;
}
}
} else {
for (int i=0; i<b.length()-1; i++) {
if (b.substring(i,i+2).equals(a.substring(i,i+2))) {
count++;
}
}
}
return count;
}
Since the substring goes from the index i (included) to i + 2 (excluded), in order not to go out of the substring the loop needs to finish 1 step before.
String.length() function returns length of the string, but when you access the characters you access it using index. That is why you have to do "-1".
For Example:
String s = "Hello";
Length is 5.
Index is from 0 to 4.
I was trying to solve a leetcode question but my solution is not returning the correct value for one of the test cases. I wanted to implement the two-pointer technique for this solution (if im using the technique wrong, advice is welcome on explaining the proper way to do it). The details are below:
Leetcode Question Title:
Longest Substring Without Repeating Characters.
Question:
Given a string, find the length of the longest substring without repeating characters. ( return int )
My Solution:
public int lengthOfLongestSubstring(String s) {
//place holder for me to create a "sub-string"
String sub = "";
//counter variable to count the characters in the substring
int count = 0;
int maxCount = 0;
//my attempt at a TWO POINTER TECHNIQUE
//pointers - to determine when the loop should break
int head = 0;
int tail = s.length();
//this variable was intended to be used with the "indexOf" method, as the "start from" index...
int index = 0;
while(head < tail){
//check if the next character in the string was already added to my substring.
int val = sub.indexOf(s.charAt(head), index);
//we proceed if it is -1 because this means the substring didnt previously contain that character
if(val == -1){
//added character to my substring
sub+= s.charAt(head);
count++;
head++;
} else {
//reset data to default conditions, while continuing at the "head index" and check the rest of the substring
count = 0;
sub = "";
}
//determine what the length of the longest substring.
maxCount = count > maxCount ? count : maxCount;
}
return maxCount;
}
I passed the test cases:
> "" = expect 0
> " " = expect 1
> "abcabcbb" = expect 3
> "bbbbb" = expect 1
> "pwwkew" = expect 3
> "aab" = expect 2
I failed test cases:
> "dvdgd" = expect 3, but got 2
> "dvjgdeds" = expect 5, but got 4
> "ddvbgdaeds" = expect 6, but got 4
Possible Issues:
I believe the issue occurred because it moves pass the index with "v", and then processes the substring "dg". So I attempted to change the solution, but fixing that issue caused all my other cases to return errors so I figured that attempt at a fix should be tossed out.
What I have also tried:
I also attempted to manipulate the "indexOf" method to change the start index, whenever the character was found in the string. This however generated an infinite loop.
I have been trying to solve this problem for a few hours and I am stomped. So any help would be appreciated greatly. And please be detailed with your explanation if you can, I am very new to DSA and programming, thank you greatly. If more information from me is needed, please let me know am I will try to answer.
Well, here you go:
public static int lengthOfLongestSubstring(String s) {
//place holder for me to create a "sub-string"
String sub = "";
//counter variable to count the characters in the substring
int count = 0;
int maxCount = 0;
//my attempt at a TWO POINTER TECHNIQUE
//pointers - to determine when the loop should break
int head = 0;
int tail = s.length();
//this variable shows where to start from
int index = 0;
while(head < tail){
//check if the next character in the string was already added to my substring.
int val = sub.indexOf(s.charAt(head)); //search whole substing
//we proceed if it is -1 because this means the substring didnt previously contain that character
if(val == -1){
//added character to my substring
sub+= s.charAt(head);
count++;
head++;
//determine what the length of the longest substring.
maxCount = count > maxCount ? count : maxCount;
System.out.println(sub); //let's see what we got so far
} else {
//reset data to default conditions, while continuing at the "head index" and check the rest of the substring
count = 0;
sub = "";
head=index+1; //begin from the next letter
index++; //move
}
}
return maxCount;
}
This question already has answers here:
checking an integer to see if it contains a zero
(7 answers)
Closed 7 years ago.
For example, we can find what we search in an array as below:
int values [] = {3, 5, 7};
for(int i = 0; i < values.length; i++)
{
if(values[i] == 3)
{
System.out.println("3 is in array.\n");
}
}
but what would happen if we search a number in integer value? Can we find what we search in that variable? I tried something with for each loop but it hasn't worked. Does Java provide this process?
int value = 151;
for(int found: value)
{
if(found == 3)
{
System.out.println("3 is in array.\n");
}
}
You could simply use String.contains():
if (Integer.toString(value).contains("3")) { ... }
I know this is not a neat way of doing it, nevertheless it is one of the ways to do it.
Steps involved:
1) Convert it to String.
2) Look for a particular character in that string using String's built in contains(CharSequence s) method
int value = 151;
//First Step:
String numberAsString = Integer.toString(value);
//Second Step:
if (numberAsString.contains('3')){
System.out.println("Found 3");
}
And remember variable value is not lost. You can use/reuse it.
Given 2 strings, a and b, return the number of the positions where they contain the same length 2 substring. For instance a and b is respectively "xxcaazz" and "xxbaaz" yields 3, since the "xx", "aa", and "az" substrings appear in the same place in both strings.
What is wrong with my solution?
int count=0;
for(int i=0;i<a.length();i++)
{
for(int u=i; u<b.length(); u++)
{
String aSub=a.substring(i,i+1);
String bSub=b.substring(u,u+1);
if(aSub.equals(bSub))
count++;
}
}
return count;
}
In order to fix your solution, you really don't need the inner loop. Since the index should be same for the substrings in both string, only one loop is needed.
Also, you should iterate till 2nd last character of the smaller string, to avoid IndexOutOfBounds. And for substring, give i+2 as second argument instead.
Overall, you would have to change your code to something like this:
int count=0;
for(int i=0; i < small(a, b).length()-1; i++)
{
String aSub=a.substring(i,i+2);
String bSub=b.substring(i,i+2);
if(aSub.equals(bSub))
count++;
}
}
return count;
Why I asked about the length of string is, it might become expensive to create substrings of length 2 in loop. For length n of smaller string, you would be creating 2 * n substrings.
I would rather not create substring, and just match character by character, while keeping track of whether previous character matched or not. This will work perfectly fine in your case, as length of substring to match is 2. Code would be like:
String a = "iaxxai";
String b = "aaxxaaxx";
boolean lastCharacterMatch = false;
int count = 0;
for (int i = 0; i < Math.min(a.length(), b.length()); i++) {
if (a.charAt(i) == b.charAt(i)) {
if (lastCharacterMatch) {
count++;
} else {
lastCharacterMatch = true;
}
} else {
lastCharacterMatch = false;
}
}
System.out.println(count);
The heart of the problem lies with your usage of the substring method. The important thing to note is that the beginning index is inclusive, and the end index is exclusive.
As an example, dissecting your usage, String aSub=a.substring(i,i+1); in the first iteration of the loop i = 0 so this line is then String aSub=a.substring(0,1); From the javadocs, and my explanation above, this would result in a substring from the first character to the first character or String aSub="x"; Changing this to i+2 and u+2 will get you the desired behavior but beware of index out of bounds errors with the way your loops are currently written.
String a = "xxcaazz";
String b = "xxbaaz";
int count = 0;
for (int i = 0; i < (a.length() > b.length() ? b : a).length() - 1; i++) {
String aSub = a.substring(i, i + 2);
String bSub = b.substring(i, i + 2);
if (aSub.equals(bSub)) {
count++;
}
}
System.out.println(count);
Im having a bit of a problem with this code each time i execute it it gives me an error
String index out of range: 'n'
n - is the no. of characters that is entered in the textbox pertaining to this code...
(that is textbox - t2.)it is stuck at that first textbox checking it does not go over to the next as mentioned in the array.
Object c1[] = { t2.getText(), t3.getText(), t4.getText() };
String b;
String f;
int counter = 0;
int d;
for(int i =0;i<=2;i++)
{
b = c1[i].toString();
for(int j=0;j<=b.length();j++)
{
d = (int)b.charAt(j);
if((d<65 || d>90)||(d<97 || d>122))
{
counter++;
}
}
}
it is basically a validation code that i am trying to do without exceptions and stuff(still in the process of learning :) )
any help would be appreciated
thx very much.
Use <, not <= when iterating over the string. With <=, you get an out of bounds error, when j equals the length of the string. Remember that characters in the string are indexed starting from zero.
for(int j = 0; j < b.length(); j++)
In java string.charAt(string.length()) will be out of bounds since the string is 0 indexed and so the last character is at string.length() - 1.
Strings are indexed starting at 0. Your second for loop is set to end at b.length, which will always be 1 greater than the highest index for that string., Change it to j < b.length instead.