I need to write a program that checks if the parenthesis are balanced, which I understand how to do and have already implemented. But, there is a second part that I'm having trouble with,
"Give an algorithm that returns the position in the string of the first offending parenthesis if the string is not properly nested and balanced That is, if an excess right parenthesis is found, return its position; if there are too many left parentheses, return the position of the first excess left parenthesis."
We haven't learned about stacks or regex so I can't utilize those. Below is my implementation to check if the nested parentheses are balanced.
public static int checkNest(char[] arr) {
int counter = 0,index = 0;
for(int i=0; i<arr.length; i++) {
if(arr[i] == '(')
counter++;
else if(arr[i] == ')')
counter--;
}
if(counter == 0)
index = -1;
return index;
}
Right now the incorrect index will always be 0, I need to manipulate my code to make the index of the incorrect parentheses correctly display.
In general, case when you have multiple parentheses' types, you have to use Stack. You have only one mistake: you should keep counter and increase it when you find an open parenthesis and decrease when finding a close one. When the counter is negative at any step of iteration - then it's not balanced`.
public static boolean isBalanced(String str) {
Deque<Character> stack = new LinkedList<>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == '(' || ch == '[' || ch == '{')
stack.push(ch);
else {
if (stack.isEmpty())
return false;
char prv = stack.pop();
if (prv == '(' && ch != ')')
return false;
if (prv == '[' && ch != ']')
return false;
if (prv == '{' && ch != '}')
return false;
}
}
return stack.isEmpty();
}
In case you have only one type of parentheses, then you could have only one counter:
public static boolean isBalanced(String str) {
int count = 0;
for (int i = 0; i < str.length() && count >= 0; i++) {
if (str.charAt(i) == '(')
count++;
else if (str.charAt(i) == ')')
count--;
}
return count == 0;
}
For an extra right parenthesis, you can immediately return the current value of i if the counter is zero, but for an extra left parenthesis, you must continue to parse the string until the end, so you must memorise the position of the last left parenthesis with counter==0:
public static int checkNest(char[] arr) {
int counter = 0,index = -1;
for(int i=0; i<arr.length; i++) {
if(arr[i] == '(') {
if (counter == 0) {
index = i;
}
counter++;
} else if(arr[i] == ')') {
if (counter == 0) {
return i;
}
counter--;
}
}
if (counter == 0) {
return -1;
}
return index;
}
public static int checkNest(char[] arr) {
int counter = 0,index = 0;
for(int i=0; i<arr.length; i++) {
// Only one incorrect parentheses.
index = i;
if(arr[i] == '(')
counter++;
else if(arr[i] == ')')
counter--;
}
if(counter == 0)
index = -1;
return index;
}
Related
The examples look like this, Input : "a-(b+c)" output "a-b-c", Input : "a-(a+b)" output "b"
I came up with this method, but the result for input: "a-(a+b)" is "a-a-b", which the correct one should be "b", how to improve that?
public String simplify(String str)
{
int len = str.length();
char res[] = new char[len];
int index = 0, i = 0;
Stack<Integer> s = new Stack<Integer> ();
s.push(0);
while (i < len) {
if (str.charAt(i) == '+') {
if (s.peek() == 1)
res[index++] = '-';
// If top is 0, append the same operator
if (s.peek() == 0)
res[index++] = '+';
} else if (str.charAt(i) == '-') {
if (s.peek() == 1)
res[index++] = '+';
else if (s.peek() == 0)
res[index++] = '-';
} else if (str.charAt(i) == '(' && i > 0) {
if (str.charAt(i - 1) == '-') {
// x is opposite to the top of stack
int x = (s.peek() == 1) ? 0 : 1;
s.push(x);
}
else if (str.charAt(i - 1) == '+')
s.push(s.peek());
}
else if (str.charAt(i) == ')')
s.pop();
else
res[index++] = str.charAt(i);
i++;
}
return new String(res);
}
I have a vector of vectors filled with characters from a text file. It is essentially a simple outbreak simulator, with 'i' characters being infected, and 's' characters being susceptible to infection. The point is to run through the matrix and if it comes across an 'i', it then changes all 's' around it into an 'i'. I run into a problem when checking the elements around it due to checking positions out of the bounds on the edges of the matrix. Is there a way to check these bounds in my if statements?
Here is the code:
for (int i = 0; i < population.size(); i++) {
for(int j = 0; j < population[i].size(); j++) {
if(population[i][j] == 'i') {
if(population[i-1][j] == 's') {
population[i-1][j] = 'i';
}
if(population[i-1][j+1] == 's') {
population[i-1][j+1] = 'i';
}
if(population[i][j+1] == 's') {
population[i][j+1] = 'i';
}
if(population[i+1][j+1] == 's') {
population[i+1][j+1] = 'i';
}
if(population[i+1][j] == 's') {
population[i+1][j] = 'i';
}
if(population[i+1][j-1] == 's') {
population[i+1][j-1] = 'i';
}
if(population[i][j-1] == 's') {
population[i][j-1] = 'i';
}
}
}
}
Instead of directly referencing a particular array entry, you could do something like the following:
void checkForInfectionAndInfectIfNeeded(int i, int j) {
for (int row = -1; row <= 1; row++) {
for (int column = -1; column <=1; column++) {
infect(i + row, j + column);
}
}
}
void infect(int i, int j) {
if (i < 0 || i >= population.size() || j < 0 || j >= population[j].size()) {
return;
} else {
population[i][j] = 'i';
}
}
This way, the infect method is the only that checks the boundaries, and you replace your long list of manually checking the surrounding locations with two loops.
I am a beginner in Java
I don't get why my if statement is wrong
public boolean sameStarChar(String str)
{
int len = str.length();
for(int x = 1; x < length-1; x++)
{
if (str.charAt(x) == '*' && str.charAt(x-1) == str.charAt(x+1))
return true;
}
else
return false;
}
Thank you
First thing start your loop from x=0 because the index of first element in 0.
str.charAt(x-1) == str.charAt(x+1)
this condition return true only if the previous and next character of * are same.
public boolean sameStarChar(String str)
{
int len = str.length();
int no=0,yes=0;
for(int x = 0; x < len-1; x++)
{
if (str.charAt(x) == '*')
{
if((str.charAt(x-1)>='a' && str.charAt(x-1)<='z') && (str.charAt(x+1)>='a' && str.charAt(x+1)<='z'))
{
yes++;
}
else{
no++;
}
}
}
if(no>0)
return false;
else
return true;
}
What I have do is that I uses a flag variable no and yes and keep track of your condition.
Hopefully that helps.
I've wrote a method/function in Java which returns the result of a given basic equation. This equation will be given as a String and I think I got this method working but don't know why I need this one line of Code because this should work without it. After trying for more than an hour to solve it I gave up and hope you can give me an aswer.
Here the Code:
public static double format(String s) {
char[] c = s.toCharArray();
if(s.contains("(")) {
int openbrackets = 0;
for (int i = 0; i < s.length() - 2; i++) {
if (c[i] == '(') openbrackets++;
else if (c[i] == ')') {
openbrackets--;
if(openbrackets == 0) {
s = s.replace(s.substring(s.indexOf('('), i+1), ""+(format(s.substring(s.indexOf('(')+1, i))));
break;
}
}
}
}
if (s.contains("(")) { // String can still contains brackets
s = "" + format(s);
}
c = s.toCharArray();
for(int i = c.length-1; i >= 0; i--) {
if(c[i] == '+') {
return format(s.substring(0, i)) + format(s.substring(i+1, s.length()));
} else if(c[i] == '-') {
return format(s.substring(0, i)) - format(s.substring(i+1, s.length()));
}
}
for(int i = s.length()-1; i > 0; i--) {
if(c[i] == '*') {
return format(s.substring(0, i)) * Double.parseDouble(s.substring(i+1, s.length()));
} else if (c[i] == '/') {
return format(s.substring(0, i)) / Double.parseDouble(s.substring(i+1, s.length()));
}
}
return s.equals("") ? 0 : Double.parseDouble(s); // I don't understand why I need to do this line
}
Description:
I don't know why I need this s.equals("") ? : because the String never should be empty however when I run it with this equation ((23)+(23-23-432-35-1-2-4231+2312+12323-(-3))*3/2) for example I get an error without it.
I need the parser to convert config Strings into Numbers for example when it comes to screenresolution. I know I can also use Libraries but I want to try these things by myself.
PS: Dont hate me just because I don't use libraries. I really tried to figure it out and I have fun doing it. I would just like to know why I have to write this little Codeline as I don't figure it out...
Edit: Error was a NumberFormatException as the Parsing got an empty String... Got my error now also the OverflowException which was mentioned in the comments...
EDIT: To everyone who MIGHT use something like this in the future:
Here the Code which actually works:
public static double format(String s) {
s = s.replace(" ", "");
s = s.replace("\t", "");
char[] c = s.toCharArray();
if(s.contains("(")) {
int openbrackets = 0;
for (int i = 0; i < s.length(); i++) {
if (c[i] == '(') openbrackets++;
else if (c[i] == ')') {
openbrackets--;
if(openbrackets == 0) {
s = s.replace(s.substring(s.indexOf('('), i+1), ""+(format(s.substring(s.indexOf('(')+1, i))));
break;
}
}
}
}
if (s.contains("(")) s = "" + format(s);
c = s.toCharArray();
for(int i = c.length-1; i > 0; i--) {
if(c[i] == '+') {
return format(s.substring(0, i)) + format(s.substring(i+1, s.length()));
} else if(c[i] == '-') {
return format(s.substring(0, i)) - format(s.substring(i+1, s.length()));
}
}
for(int i = s.length()-1; i > 0; i--) {
if(c[i] == '*') {
return format(s.substring(0, i)) * Double.parseDouble(s.substring(i+1, s.length()));
} else if (c[i] == '/') {
return format(s.substring(0, i)) / Double.parseDouble(s.substring(i+1, s.length()));
}
}
return s.equals("") ? 0 : Double.parseDouble(s);
}
I'm fairly sure this is at least one location in your code where you pass a 0 length string to your format function:
c = s.toCharArray();
for(int i = c.length-1; i >= 0; i--) {
if(c[i] == '+') {
return format(s.substring(0, i)) + format(s.substring(i+1, s.length()));
} else if(c[i] == '-') {
return format(s.substring(0, i)) - format(s.substring(i+1, s.length()));
}
}
Your loop counter in (int i = c.length-1; i >= 0; i--) will get decremented until it is 0 in value if there are no + or - values in the input string.
Then you call format(s.substring(0, i)) where i = 0 so I think this is one place where you will be passing a zero length/empty string to your function.
Please use a debugger and step through your code - not only would it teach you a valuable skill it would also probably give you the answer you're looking for.
I need to check if an array contains a 1 and then later in the array contains a 2.
What I have coded only checks if both are in there, not if one is before the other. How could I do this?
if(array[i] == 1)
count++;
else if(array[i] == 2)
count++;
}
if(count > 1)
System.out.print("true");
else
System.out.print("false");
Comparing the index of the values works!
if (nums[i] == 1)
value1 = i;
else if(nums[i] == 2)
value2 = i;
}
if (value2 > value1)
System.out.print("true");
else
System.out.print("false");
This oughta do it!
public void hasOneThenTwo(int[] a) {
bool hasOne = false;
for (int i = 0; i < a.length; ++i) {
if (!hasOne && a[i] == 1) {
hasOne = true;
} else if (hasOne && a[i] == 2) {
return true;
}
}
return false;
}