Brute force: count number of sub strings in a string array - java

What I am supposed to do is create an algorithm that counts the number of substrings in a piece of text where the substrings can be the letter B followed by C or C followed by B. I'm not sure what to do, but I tried it and came up with the result below. I'd like to know if I did it correctly.
int substrCount(String S[0...n-1]){
int count = 0;
for (int i = 0; i<=n-2; i++) {
for (int j=i+1; j<i+2; j++) {
if ((S[i] == 'B' && S[j] == 'C' ) || (S[i] == 'C' && S[j] == 'B')) {
count = count + 1;
}
}
}
}
I am gonna ignore whether it includes lowercase or uppercase for now. I also need to find the complexity of the algorithm from which I believe it is O(n^(2)). Did I do this correctly? If so, can I make it any more efficient?

This works well for me
static int substrCount( String str) {
int count=0;
for (int i=0; i<str.length()-1; i++)
{
boolean bc = (str.charAt(i) == 'B' && str.charAt(i+1) == 'C');
boolean cb = (str.charAt(i) == 'C' && str.charAt(i+1) == 'B');
if (bc || cb) {
count++;
}
}
return count;
}
You need to loop the sequence of chars in string just once to get the desired result. Check the couple of chars if they are equal "BC" or "CB" and move one index forward to the end of the string.
Output example:
"ACBAA" gives result 1
"ABCBA" gives result 2
"BCBCB" gives result 4
"BBBBB" gives result 0

Related

Trying to remove multiple specific char from a StringBuilder in s specific way [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
I'm trying to remove every "x" regardless of case only from the first and second index but my program only removes the first index's letter and then loops without removing the second one.
Scanner userIn = new Scanner(System.in);
StringBuilder str = new StringBuilder();
str.append(userIn.nextLine());
for(int i = 0; i<2; i++) {
if((str.charAt(i) == 'x') || (str.charAt(i) == 'X')) {
str = str.deleteCharAt(i);
}
}
System.out.println(str);
This is because when you delete a letter at the beginning all the characters shift. So for String str = "xxHello";:
x x H e l l o
0 1 2 3 4 5 6
Then when you delete the first x:
x H e l l o
0 1 2 3 4 5
So on your second iteration it will check to see if the first index (In this case H) is X. To fix this you can set i to 1 and then loop to zero:
StringBuilder str = new StringBuilder();
str.append(userIn.nextLine());
for(int i = 1; i> -1; i--) {
if((str.charAt(i) == 'x') || (str.charAt(i) == 'X')) {
str = str.deleteCharAt(i);
}
}
System.out.println(str);
Output:
Hello
Imagine that your input string is "XXY". Let's step through your code:
for(int i = 0; i<2; i++) {
if((str.charAt(i) == 'x') || (str.charAt(i) == 'X')) {
str = str.deleteCharAt(i);
}
}
On the first iteration, i is equal to 0, so we check if the first character in the string is equal to 'x' or to 'X'. The first character of "XXY" is in fact equal, so we execute the contents of the if statement:
str = str.deleteCharAt(i);
Now our string is "XY". And now we go through the loop again.
On the second iteration, i is equal to 1, so we check the second character in the string. But now our string is "XY", so the second character is 'Y' and the if check fails.
You could use str.delete(start, end) instead of the loop. For example:
String substr = str.substring(0,2).toLowerCase();
str.delete(
substr.indexOf('x'),
substr.lastIndexOf('x')+1
);
Since there are only first two deletion to be done so inbuilt function can be used :
Scanner userIn = new Scanner(System.in);
StringBuilder str = new StringBuilder();
str.append(userIn.nextLine());
int j=0;
for(int i = 0; i<2; i++) {
if((str.charAt(j) == 'x') || (str.charAt(j) == 'X')) {
str = str.deleteCharAt(j);
}else{
j++;
}
}
System.out.println(str);

Java String Explanation needed

Hey can someone please explain this coding line by line?
public boolean twoE(String str) {
int count = 0;
for (int i=0; i<str.length(); i++) {
if (str.charAt(i) == 'e')
count++;
}
if (count == 2){
return true;
}
return false;
// this last if/else can be written simply as "return (count == 2);"
}
public boolean twoE(String str) {
Declares method twoE that takes the argument str of type String.
int count = 0;
Creates a variable named count of type int and initializes it to 0.
for (int i=0; i<str.length(); i++) {
Uses a for loop to iterate from 0 - the length of the string (str.length()).
if (str.charAt(i) == 'e') count++;
Checks if the the ith letter (str.charAt(i)) of str is a 'e'. If so, increment the count.
if (count == 2) return true;
return false;
If there were 2 'e's, then return true, otherwise, return false.
Note You might not have written this code, but if you did I have one suggestion. Change the last line to return (count == 2); to save space and make the meaning more clear.
The summary of what this function does is that it returns a boolean (true or false) whether or not the String argument passed in contains exactly two lowercase e characters.
How it achieves this is as follows:
Initialize an empty count of 0
Loop through every character of the string
For each character, if the character is a lowercase e, add 1 to the counter
After you are done looping, check what the count was.
If the count was exactly 2, return true, otherwise, return false.

Why is my for-loop not functioning? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm making a program that counts the number of vowels in a phrase that was assigned by my teacher. To do this I have made a for-loop that in theory should check each character for being a, then e, the i, and so on before moving on to the next character. For some reason though nothing in the for-loop works. The build output states that everything is fine, but the for-statements aren't functioning properly. I know that t actually is the correct letter because I printed what t was but the for loop still won't work. What confuses me is the build output is fine, so it must be a logic error, but I can't find where it is. Here is the code:
for (i = 0; i != phrase.length(); i++) {
String t = phrase.substring(i, i + 1);
if (t == "a") {
count++;
System.out.println(count);
}
if (t == "e") {
count++;
}
if (t == "i") {
count++;
}
if (t == "o") {
count++;
}
if (t == "u") {
count++;
}
}
System.out.println(count);
Many thanks to anyone who can help me!
the exit condition is wrong, try:
for (i = 0 ; i < phrase.length(); i++) {
You have several issues in your code.
1) First issue being the i == phrase.length(). This is the until condition. Change this to i <= phrase.length(). *
In your case this would have worked but it's better to do it right. Normally you check on values here that could for example grow bigger than 10 and if you skip 10 and keep counting you would enter an infinite loop. So always use <= or >=.
*edit: Correction you should use < since you have a substring working with i+1.
2) Don't use == for String (or any other object) comparison. That will compare the memory address instead. For String use the equals() method.
Also make sure to put the known literal "a", "b" and so up front since you could get a nullpointer exception otherwise.
3) It might be better to go for a charAt(0) first and then use == since you can compare char (primitive) values.
4) I also combined the if statements in one.
String phrase = "WazzUp ? Who’s On FIRST??? IDUNNO";
phrase = phrase.toLowerCase();
System.out.println("value of phrase is: "+phrase);
int count = 0;
for (int i = 0 ; i < phrase.length() ; i++) {
String t = phrase.substring(i, i + 1);
if ("a".equals(t) || "e".equals(t) || "i".equals(t) || "o".equals(t) || "u".equals(t) ) {
count++;
}
}
System.out.println("value of count is: "+count);
Check the for exit condition and String comparison, which should be done using equal: if ("a".equals(t)) { ... }.
Your for-decleration is wrong.
It should be
for(<startexpression> ; <any expression, that is still true> ; in-/decrement>)
In your case you start with i=0, so on the same run i cannot equal phrase.length()in your case. This is why you code does not get executet.
Try:
for (i = 0 ; i < phrase.length(); i++) {
instead.
Also, when comparing string, you should use
String.equals("whatever")
instead of the equeals-operator (=).
In your for loop, shouldn't it be i = phrase.length() instead of i ==? i == is doing comparison instead of setting i equal to (i = sets it equal to something instead of comparing)
As to what emilioicai said your conditions is wrong
for (i = 0 ; i == phrase.length(); i++) { <----! Wrong
for (i = 0 ; i < phrase.length(); i++) { <---- Correct
Also strings Should be compared with equals, so instead of this
if (t == "a") {
count++;
System.out.println(count);
}
You should have this
if ("a".equals(t)) {
count++;
System.out.println(count);
}
And if you want to go fancy you can do something like this :)
String phrase = "WazzUp ? Who’s On FIRST??? IDUNNO";
phrase = phrase.toLowerCase();
System.out.println("value of phrase is: "+phrase);
int count = 0;
String[] characters = new String[] {"a", "e", "i", "o", "u"};
for (int i = 0 ; i < phrase.length() ; i++) {
String t = phrase.substring(i, i + 1);
for(String character : characters){
if(character.equals(t)){
count++;
}
}
}
System.out.println("value of count is: "+count);
The above makes code nicer, more scalable, and easier to read
There are two errors about your code.
First, for (i = 0 ; i < phrase.length(); i++) {}
Second, if (t .equals("a")) { but not if (t == "a") {
try this:
for (i = 0; i != phrase.length(); i++) {
String t = phrase.substring(i, i + 1);
System.out.println(t);
if (t.equals("a")) {
count++;
System.out.println(count);
}
if (t.equals("e")) {
count++;
}
if (t.equals("i")) {
count++;
}
if (t.equals("o")) {
count++;
}
if (t.equals("u")) {
count++;
}
}
by the way, it's more common to change your condition to this:
i < phrase.length()
since it shows the progress better and increases the readability of your code.
Make it this way
String phrase = "WazzUp ? Who’s On FIRST??? IDUNNO";
phrase = phrase.toLowerCase();
int count = 0;
int i = 0;
System.out.println(phrase);
for (i = 0 ; i < phrase.length(); i++) {
String t = phrase.substring(i, i + 1);
if (t == "a") {
count++;
System.out.println(count);
}
if (t == "e") {
count++;
}
if (t == "i") {
count++;
}
if (t == "o") {
count++;
}
if (t == "u") {
count++;
}
}
System.out.println(count);

Need help understanding parts of this class

I need someone to elaborate on certain parts of this code.
class ContinueWithLabelDemo {
public static void main(String[] args) {
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() -
substring.length();
test:
for (int i = 0; i <= max; i++) {
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
}
more specifically, I don't understand this part:
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
Why is it necessary to declare j and k in this code at all? I know that there is a reason in it for the if statement
if (searchMe.charAt(j++) != substring.charAt(k++))
but I don't understand what the code is actually doing at this part.
Also, what does
while (n-- != 0)
mean?
while (n-- != 0)
This is just looping around, reducing n by 1 each time around the loop and ending when n (before) reducing it by 1 is not 0.
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
This code is starting with j and k at different positions in the string, and then it is looping through comparing the character in the String at that position. j++ just says "use the current value of j, and then afterwards add 1 to it".
++ and -- are pre or post incrementor and decrementor in java.
Imagine the following code to understand the behaviour:
int a = 42
System.out.println(a++) // prints 42
System.out.println(a) // prints 43
System.out.println(++a) // prints 44
System.out.println(a) // prints 44
In fact, it adds or subtracts 1 before or after the statement is processed.
So in your situations, while (n-- != 0) means, that the condition is checked, wether n is not zero and after that decremented by 1.
To achieve the same, you could also write:
while (n != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
n = n - 1 // or n-- or n -= 1
}
Your second condition if (searchMe.charAt(j++) != substring.charAt(k++)) compares the character at the index j in searchMe against the character with the index k from substring and after that increments both indices to avoid two more lines, where these two are incremented.
Well, this is some interesting code. To start off, the label on your break is unnecessary.
Next, to your main questions:
n-- is a postfix decrement operator - the current value of n is evaluated, then it is decremented by 1. When n is evaluated next, it will have the value of n-1.
In the context of the code while(n-- != 0) implies that, when n == 1, this loop will still execute, but the next time we see n, we will be viewing 0 instead.
The statement:
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
...indicates that, if the value in the position of the main search string doesn't match up with the value we're looking for, we need to immediately jump to the label test. This allows you to skip the execution of the following two statements after it, and continue looping and looking for positive matches.
j is constantly set to what i is, but it is not always equal to i. If a partial positive match is found, then j will increment faster than i by virtue of the while loop around that statement.
This can be broken down in to the following:
outer: loop(/* for each character in searchMe to max */) {
loop(/* for each character in substring
* starting with current index in outer loop */) {
if(/* this substring does not match */)
continue /* with next outer loop iteration */;
}
/* if inner loop completed
* the substring did match at this index so break */;
}
Out of all the variables, n is actually the one that's not needed. I don't know why it's there except to try to confound. The while loop could just as easily read while(k < substring.length()).
This kind of loop is necessary because to search for a substring you have to search starting at every character:
Loo
ook
ok
k f
fo
for
or
r a
...
a s
su
sub <- found it
Another way to express the same logic is the following but this creates a new object on each iteration:
int max = searchMe.length() - substring.length();
for(int i = 0; i <= max; i++) {
String toTest = searchMe.substring(i, i + substring.length());
if(toTest.equals(substring)) {
foundIt = true;
break;
}
}
Starting with an n >= 0 (string length can not be negative):
while (n-- != 0) {
...
}
is just a substitute for
for (int t = n ; t > 0; t--) {
.... // use t instead of n, no change in your example
}
it iterates just n times (length of substring).
class ContinueWithLabelDemo {
public static void main(String[] args) {
String searchMe = "Look for a substring in me";
String substring = "sub";
boolean foundIt = false;
int max = searchMe.length() -
substring.length(); //the length of what we're going to search through, we
//subtract the substring.Length because if the 3rd to
//last character of searchMe is not equal to the first
//character of substring then searchMe can not contain substring.
test:
for (int i = 0; i <= max; i++) { //repeat until we pass the 3rd to last character of searchMe
int n = substring.length(); //resets n to the length of the substring
int j = i; //resets j to equal i so we search for the next letter in searchMe
int k = 0; //resets k to equal 0 so we search for the first letter in substring
while (n-- != 0) { //repeat this loop until n = 0, each pass will subtract 1 from
//n. this will loop a maximum of 3 times (the number of characters in substring)
if (searchMe.charAt(j++) != substring.charAt(k++)) {
//the if statement above will add 1 to j and add 1 to k after it checks to make sure the
//characters are not equal to each other. if they are equal then it will take the new
//j and k variables and repeat the while loop.
continue test; //if statement true then loop through the 'test' again.
}
}
foundIt = true;
break test;
}
System.out.println(foundIt ? "Found it" : "Didn't find it");
}
}
Oracle doesn't know how to write simple things in a tutorial for beginners.
This part:
int n = substring.length();
int j = i;
int k = 0;
while (n-- != 0) {
if (searchMe.charAt(j++) != substring.charAt(k++)) {
continue test;
}
}
can be changed to:
int n = substring.length();
for (int k = 0; k < n; k++) {
if (searchMe.charAt(i + k) != substring.charAt(k)) {
continue test;
}
}
So, you don't need j and instead of that tricky while you can use a simple for which is more intuitive, because it iterates through the substring.

Java Counting letter,digit and symbol

I want to count the number of letter, digit and symbol using JAVA
However the result output is not ideal. it should be 5,2,4
but I got 5,2,13
int charCount = 0;
int digitCount = 0;
int symbol = 0;
char temp;
String y = "apple66<<<<++++++>>>";
for (int i = 0; i < y.length(); i++) {
temp = y.charAt(i);
if (Character.isLetter(temp)) {
charCount++;
} else if (Character.isDigit(temp)) {
digitCount++;
} else if (y.contains("<")) {
symbol++;
}
}
System.out.println(charCount);
System.out.println( digitCount);
System.out.println( symbol);
It should be
} else if (temp == '<')) {
symbol++;
}
In your solution, for every non-letter-or-digit character you check if the entire string contains <. This is always true (at least in your example), so the result you get is the number of special characters in the string.
You should use y.charAt(i) == '<' rather than y.contains("<")
if you use y.contains("<"), it uses the whole string to check whether it contains '<' or not. Since String y contains '<'. When in for loop, there are 4 '<', 6 '+' and 3 '>'.
For checking such charraters, y.contains("<") always be true. That is why you get 13 (=4+6+3) for symbol rather than 4.
This bit is wrong:
y.contains("<")
You are checking the whole string each time when you only want to check a single character (temp)
int charCount = 0;
int digitCount = 0;
int symbol = 0;
char temp;
String y = "apple66<<<<++++++>>>";
for (int i = 0; i < y.length(); i++) {
temp = y.charAt(i);
if (Character.isLetter(temp)) {
charCount++;
} else if (Character.isDigit(temp)) {
digitCount++;
****} else if (temp =="<") {
symbol++;
}
}****
else if (y.contains("<")) {
should be
else if (temp == '<') {
because else every time youu have no letter or digit it is raised.
y.contains("<")
seaches for the substring "<" in the string "apple66<<<<++++++>>>" and it always finds it. This happens 13 times which is the number of chars in the substring <<<<++++++>>>" which does contains neither a letter nor a digt.

Categories