Java Balanced String not using stack - java

I need to check if given String is balanced or not.
This is similar task like that one with balanced parenthesis.
Please let me know if this is understand for you.

try this
public class CheckBalance {
public static void main(String[] args) {
System.out.println(check("asdfgh()hgfdsa"));
}
static boolean isClosing(char first, char sec)
{
if (first == '(' && sec == ')') {
return true;
} else if (first == '{' && sec == '}' ) {
return true;
} else if (first == '[' && sec == ']') {
return true;
}//add other the different Chars
else if(first == sec){
return true;
}
return false;
}
static boolean check(String value) {
if (value != null) {
char[] valueAsArray = value.toCharArray();
int size = valueAsArray.length;
if (size == 0) {
return true;
} else if (size == 1) {
return true;
} else {
for (int i = 0; i < size; i++) {
if (!isClosing(valueAsArray[i], valueAsArray[size - (i+1)])){
return false;
}
if (i == (size-1)/2) {
break;
}
}
return true;
}
} else {
return true;
}
}
}

public boolean isBalanced(String s) {
return isBalanced(s, 0, new LinkedList<>());
}
private boolean isBalanced(String s, int index, LinkedList<Character> stack) {
if (index >= s.length())
return stack.isEmpty();
char c = s.charAt(index);
if (!stack.isEmpty() && Character.compare(c, stack.getLast()) == 0) {
stack.removeLast();
if (isBalanced(s, index + 1, stack))
return true;
stack.add(c);
}
stack.add(c);
return isBalanced(s, index + 1, stack);
}

ABAB is wrong right ? it is the same with parenthesis ?
public boolean isBalanceString(String input)
{
int firstIndex =0;
int lastIndex = input.length()-1;
while (firstIndex<lastIndex)
{
if(input.charAt(firstIndex) != input.charAt(lastIndex))
{
return false;
}
firstIndex++;
lastIndex--;
}
return true;
}

Related

Trying to implement a stack and the bracket matching problem but cannot figure out some semantic errors

I am required to write my own stack using an array which then I have to implement the bracket matching problem.
This is my algorithm: if we're given the string: "(())" it is returning "not balanced" when it should say it is "balanced". If you look over at BracketCheck.java near the end it tests whether the stack is empty where if it is it should return true and say the given string: "(())" is balanced. I am having problems debugging it and the result of the operation is incorrect.
Here is my stack and main class code:
public class Stack {
// instance fields:
private char array[]; // our array
private int topOfStack; // this indicates the value for each position
// overloaded constructor:
public Stack(int size) {
this.array = new char[size]; // here we instantiate a new char type array.
this.topOfStack = -1; // we set the starting position of the topOfStack to -1.
}
// push method:
public void push(char character) {
if(isFull() == true) {
System.out.println("Stack overflow error.");
}
else {
topOfStack++;
array[topOfStack] = character;
}
}
// pop method:
public char pop() {
if(isEmpty() == true) {
//System.out.println("Overflow.");
return '\0';
}
else {
char c = array[topOfStack];
topOfStack--;
return c;
}
}
// top method:
public int top() {
if(isEmpty() == true) {
System.out.println("The stack is empty.");
return 0;
}
else {
return array[topOfStack]; // returns the top element in the stack.
}
}
// size method:
public int size() {
return topOfStack + 1;
}
// isEmpty method:
public boolean isEmpty() {
if(topOfStack == -1) {
return true;
}
else {
return false;
}
}
// isFull method:
public boolean isFull() {
if(topOfStack == array.length -1 ) {
System.out.println("Stack if full.");
return true;
}
else {
return false;
}
}
BracketCheck.java
public class BracketCheck {
public static void main(String args[]) {
String text = "(())";
//boolean check = isBalanced(text);
if(isBalanced(text) == true) {
System.out.println("Balanced.");
}
else {
System.out.println("Not balanced");
}
}
public static boolean isBalanced(String text) {
Stack stack = new Stack(25); // for simplicity our stack is going to be a size of 25.
char[]arr = text.toCharArray(); // convert our string to a set of characters in an array.
// here we are looping through our text
for(int i = 0; i < arr.length; i++) {
if(arr[i] == '{' || arr[i] == '(' || arr[i] == '[') {
stack.push(arr[i]);
}
else if(arr[i] == '}' || arr[i] == ')' || arr[i] == ']') {
if(stack.isEmpty()) {
return false; // if empty then return false.
}
else if((stack.pop() == '(' && arr[i] != ')') || (stack.pop() == '{' && arr[i] != '}') || (stack.pop() == '[' && arr[i] != ']')) {
return false; // here we return false because this tells us that there is a mismatch and not balanced. Also if we did pop out the brace and it was equal
// to it's corresponding closing brace then it will just continue the loop other return false to indicate it is unbalanced.
}
}
}
if(stack.isEmpty()) {
return true; // after looping through the text if the stack turns out to be empty then this shows that there the text is balanced indeed because
}
else {
return false;
}
}
}
In this condition
else if((stack.pop() == '(' && arr[i] != ')') || (stack.pop() == '{' && arr[i] != '}') || (stack.pop() == '[' && arr[i] != ']')) {
You pop 3 times, so you extract 3 different elements from your stack. To fix it, pop once and save popped element in local variable:
if(stack.isEmpty()) {
return false; // if empty then return false.
}
else {
char element = stack.pop();
if((element == '(' && arr[i] != ')') || (element == '{' && arr[i] != '}') || (element == '[' && arr[i] != ']')) {
return false;
}
}

Interpreter design function issues (eclipse)

My code is faulty in that it doesn't evaluate each word of the sentence entered by the user.
The interpreter must read from a file the instructions of a program written. In
case of an error in an instruction, the interpreter must stop and show the line number of the instruction that provoked the error.
Am I missing a library for the error message? I've heard Maven has tools that does exactly that, have you?
Click here to see ideal sample output.
Click here to see program description.
public class TokenVerifier {
public static String askInput() {
Scanner input = new Scanner(System.in);
return input.nextLine();
};
public static boolean isString (String str) {
int i = 0, last = str.length() - 1;
if(str.isEmpty())
return false;
if(str.charAt(i) == '"' && (str.charAt(last)) == '"') {
return true;
}
return false;
}
public static boolean logical(String in) {
String str = in.toUpperCase();
boolean result = false;
if(str.equals(".OR.") || str.equals(".AND.")|| str.equals(".NOT.")) {
result = true;
}
return result;
}
public static boolean rem(String in) {
String str = in.toUpperCase();
boolean result = false;
if(str.equals("REM")) {
result = true;
}
return result;
}
public static boolean print(String in) {
String str = in.toUpperCase();
boolean result = false;
if(str.equals("PRINT")) {
result = true;
}
return result;
}
public static boolean read(String in) {
String str = in.toUpperCase();
boolean result = false;
if(str.equals("READ")) {
result = true;
}
return result;
}
public static boolean isIf(String in) {
String str = in.toUpperCase();
boolean result = false;
if(str.equals("IF")) {
result = true;
}
return result;
}
public static boolean isThen(String in) {
String str = in.toUpperCase();
boolean result = false;
if(str.equals("THEN")) {
result = true;
}
return result;
}
public static boolean isEnd(String in) {
String str = in.toUpperCase();
boolean result = false;
if(str.equals("END")) {
result = true;
}
return result;
}
public static boolean relational(String in) {
String str = in.toUpperCase();
boolean result = false;
if(str.equals(".GT.") || str.equals(".LT.")|| str.equals(".EQ.")||str.equals(".GE.")||str.equals(".LE.")||str.equals(".NE.")) {
result = true;
}
return result;
}
public static boolean arithmetic(String in) {
String str = in.toUpperCase();
boolean result = false;
if(str.equals(".ADD.") || str.equals(".SUB.")|| str.equals(".MUL.")||str.equals(".DIV.")) {
result = true;
}
return result;
}
public static boolean sign(String in) {
boolean result = false;
char[] chars = in.toCharArray();
if (in.isEmpty())
return false;
if(chars[0] == '+' ||chars[0] == '-')
result = true;
return result;
}
public static boolean alphabet(String name) {
char[] chars = name.toCharArray();
if (name.isEmpty())
return false;
for (char c : chars) {
if(!Character.isLetter(c)) {
return false;
}
}
return true;
}
public static boolean digit(String name) {
char[] chars = name.toCharArray();
if (name.isEmpty())
return false;
for (char c : chars) {
if(!Character.isDigit(c)) {
return false;
}
}
return true;
}
public static boolean variable(String in) {
int i = 0;
String temp = in.toUpperCase();
if(temp.equals("REM") ||temp.equals("READ")||temp.equals("PRINT")||temp.equals("IF")||temp.equals("THEN")|| temp.equals("END"))
return false;
if(alphabet(in)) {
if( (in.charAt(i) >= 'a' && in.charAt(i) <= 'f') || (in.charAt(i) >= 'A' && in.charAt(i) <= 'F'))
System.out.println(" Integer Type");
if( (in.charAt(i) >= 'g' && in.charAt(i) <= 'n') || (in.charAt(i) >= 'G' && in.charAt(i) <= 'N'))
System.out.println(" Real Number Variable");
if( (in.charAt(i) >= 'o' && in.charAt(i) <= 'z') || (in.charAt(i) >= 'O' && in.charAt(i) <= 'Z'))
System.out.println("String Variable");
return true;
}
return false;
}
public static boolean unsignedInteger(String in) {
if(digit(in))
return true;
return false;
}
public static boolean signedInteger(String name) {
if(sign(name)) {
char[] chars = new char[name.length()-1];
int start = 0;
for(int i = 1;i <= name.length() - 1;i++){
chars[start] = name.charAt(i);
start++;
}
String str = new String(chars);
if(digit(str))
return true;
}
return false;
}
public static boolean decimalPoint(String in) {
char[] chars = in.toCharArray();
int count = 0;
if (in.isEmpty())
return false;
if(chars[0] == '.'|| chars[in.length() - 1] == '.')
return false;
for(int i = 0; i <= in.length() - 1;i++) {
if(chars[i] == '.') {
count++;
}
}
if(count == 1)
return true;
return false;
}
public static boolean realUnsigned(String in) {
String unsignedPart = "", decimalPart = "",intPart = in.toUpperCase(), realPart = "";
int indexOfPoint = 0;
if (in.isEmpty())
return false;
if (sign(intPart) == false){
if(exponent(intPart)) {
realPart = intPart.substring(0, intPart.indexOf('E'));
if(decimalPoint(realPart)) {
unsignedPart = realPart.substring(1, intPart.indexOf('.'));
indexOfPoint = realPart.indexOf('.');
decimalPart = realPart.substring(indexOfPoint + 1);
if(digit(unsignedPart)&&digit(decimalPart))
return true;
}
}
else {
if(decimalPoint(in)) {
unsignedPart = in.substring(1, intPart.indexOf('.'));
indexOfPoint = in.indexOf('.');
decimalPart = in.substring(indexOfPoint + 1);
if(digit(unsignedPart)&&digit(decimalPart))
return true;
}
}
}
return false;
}
public static boolean realSigned(String in)
{
String unsignedPart = "", decimalPart = "",intPart = in.toUpperCase(), realPart = "";
int indexOfPoint = 0;
if (in.isEmpty())
return false;
if (sign(intPart)){
if(exponent(intPart)) {
realPart = intPart.substring(0, intPart.indexOf('E'));
if(decimalPoint(realPart)) {
unsignedPart = realPart.substring(1, intPart.indexOf('.'));
indexOfPoint = realPart.indexOf('.');
decimalPart = realPart.substring(indexOfPoint + 1);
if(digit(unsignedPart)&&digit(decimalPart))
return true;
}
}
else {
if(decimalPoint(in)) {
unsignedPart = in.substring(1, intPart.indexOf('.'));
indexOfPoint = in.indexOf('.');
decimalPart = in.substring(indexOfPoint + 1);
if(digit(unsignedPart)&&digit(decimalPart))
return true;
}
}
}
return false;
}
public static boolean exponent(String in) {
String unsignedPart = "", decimalPart = "",str = in.toUpperCase(), afterExponent ="";
int indexOfPoint = 0, indexOfExponent = 0;
char[] chars = str.toCharArray();
int count = 0;
if (in.isEmpty())
return false;
for(int i = 0; i <= str.length() - 1;i++) {
if(chars[i] == 'E') {
count++;
}
if(count == 1) {
indexOfExponent = str.indexOf('E');
if(str.length()-1 == indexOfExponent)
return false;
afterExponent = str.substring(indexOfExponent + 1);
if(decimalPoint(afterExponent)) {
if(sign(afterExponent)) {
unsignedPart = afterExponent.substring(1, afterExponent.indexOf('.'));
indexOfPoint = afterExponent.indexOf('.');
decimalPart = afterExponent.substring(indexOfPoint + 1);
if(digit(unsignedPart)&&digit(decimalPart))
return true;
}
else {
unsignedPart = afterExponent.substring(0, afterExponent.indexOf('.'));
indexOfPoint = afterExponent.indexOf('.');
decimalPart = afterExponent.substring(indexOfPoint + 1);
if(digit(unsignedPart)&&digit(decimalPart))
return true;
}
}
}
}
return false;
}
public static boolean tokenVerifier(String input) {
if(logical(input))
return true;
if(relational(input))
return true;
if(variable(input))
return true;
if(isString(input))
return true;
if(unsignedInteger(input))
return true;
if(signedInteger(input))
return true;
if(realUnsigned(input))
return true;
if(realSigned(input))
return true;
if(arithmetic(input))
return true;
if(rem(input))
return true;
if(print(input))
return true;
if(read(input))
return true;
if(isEnd(input))
return true;
if(isThen(input))
return true;
if(isIf(input))
return true;
return false;
}
/**********************************************************************************************************************************************************/
/**************************************************************** SENTENCE VERIFIER *****************************************************************/
public static boolean sentenceVerifier(String in) {
String tokens[] = in.split(" ");
int indexOfStringArray = tokens.length;
for(int i = 0; i <= indexOfStringArray - 1; i++) {
if(tokenVerifier(tokens[i]))
System.out.print("Token");
else
System.out.print("Not Token");
}
return false;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String in = input.nextLine();
sentenceVerifier(in);
}
}

how to check number exists between braces

import java.util.Stack;
import java.util.Scanner;
public class CheckValidLocationofParenthensies {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter five data");
String input1 = scanner.next();
balancedParenthensies(input1);
}
public static boolean balancedParenthensies(String s) {
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == '[' || c == '(' || c == '{' ) {
stack.push(c);
if(c == '[') {
newvalueforforward(s,']', i);
}
if(c == '{') {
newvalueforforward(s,'}', i);
}
if(c == '(') {
newvalueforforward(s,')', i);
}
} else if(c == ']') {
if(stack.isEmpty() || stack.pop() != '[') {
newvalue(s,'[', i);
return false;
}
} else if(c == ')') {
if(stack.isEmpty() || stack.pop() != '(') {
newvalue(s,'(', i);
return false;
}
} else if(c == '}') {
if(stack.isEmpty() || stack.pop() != '{') {
newvalue(s,'{', i);
return false;
}
}
}
return stack.isEmpty();
}
public static void newvalueforforward(String userval,char value,int decremntval) {
for(int i = 0; i < userval.length(); i++){
StringBuilder newvalue = new StringBuilder(userval);
int location=i;
newvalue.insert(i, value);
boolean valid= checkingnewvalueisValidorNot(newvalue, location);
location=i+1;
if(valid) {
System.out.println(newvalue+" "+""+location);
}
}
}
public static void newvalue(String userval,char value,int decremntval) {
for(int i = decremntval; i >= 0; i--){
StringBuilder newvalue = new StringBuilder(userval);
int location=decremntval - i;
newvalue.insert(decremntval - i, value);
boolean valid= checkingnewvalueisValidorNot(newvalue, location);
if(valid) {
System.out.println(newvalue+" "+""+location);
}
}
}
public static boolean checkingnewvalueisValidorNot(StringBuilder userval,int validpath) {
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < userval.length(); i++) {
char c = userval.charAt(i);
if(c == '[' || c == '(' || c == '{' ) {
stack.push(c);
} else if(c == ']') {
if(stack.isEmpty() || stack.pop() != '[') {
return false;
}
} else if(c == ')') {
if(stack.isEmpty() || stack.pop() != '(') {
return false;
}
} else if(c == '}') {
if(stack.isEmpty() || stack.pop() != '{') {
return false;
}
}
}
return stack.isEmpty();
}
}
Above is the code i have written to check whether input string contains all balanced brackets if it is not balanced then get missing bracket and place bracket in all index then again check whether string is balanced or not.
I got valid output but problem is between i bracket there should be a intergers
here is input and outputs
input missing outputs
{[(2+3)*6/10} ] {[](2+3)*6/10} 3 not valid(no numbres btn bracket)
{[(2+3)]*6/10} 8 valid
{[(2+3)*]6/10} 9 not valid(after * no number)
{[(2+3)*6]/10} 10 valid
{[(2+3)*6/]10} 11 not valid( / before bracket)
{[(2+3)*6/1]0} 12 not valid( / btn num bracket)
{[(2+3)*6/10]} 13 valid
i am failing to do proper validation to my output.
Before the bracket there may be:
number
closing bracket
After the bracket there may be:
operator
closing bracket
end of expression
(ignoring any whitespace)

infinite loop in siftDown method for a heap using linked nodes

In my siftDown method for my heap, I'm getting an infinite loop I believe that is being caused by my if(current.isLeaf()) line. Can anyone help me so that I can get Node n down to where it becomes a leaf or when it stops being smaller than its children?
public void siftDown(Node<V> n) {
Node<V> current = n;
boolean notDone = true;
while (notDone) {
if (!current.isLeaf()) {
current = n;
if ((current.data.compareTo(current.left.data) < 0)
&& (current.left.data.compareTo(current.right.data) >= 0)) {
swapValues(current, current.left);
current = current.left;
} else if ((current.data.compareTo(current.right.data) < 0)
&& (current.right.data.compareTo(current.left.data) > 0)) {
swapValues(current, current.right);
current = current.right;
if (current.isLeaf()) {
notDone = false;
}
}
} else {
notDone = false;
}
}
}
public void swapValues(Node<V> x, Node<V> y) {
V temp = x.data;
x.data = y.data;
y.data = temp;
}
public boolean isLeaf() { //inside my node class
if (left == null && right == null)
return true;
else
return false;
}

Verify if String matches real number

I'm trying to verify if a String s match/is a real number. For that I created this method:
public static boolean Real(String s, int i) {
boolean resp = false;
//
if ( i == s.length() ) {
resp = true;
} else if ( s.charAt(i) >= '0' && s.charAt(i) <= '9' ) {
resp = Real(s, i + 1);
} else {
resp = false;
}
return resp;
}
public static boolean isReal(String s) {
return Real(s, 0);
}
But obviously it works only for round numbers. Can anybody give me a tip on how to do this?
P.S: I can only use s.charAt(int) e length() Java functions.
You could try doing something like this. Added recursive solution as well.
public static void main(String[] args) {
System.out.println(isReal("123.12"));
}
public static boolean isReal(String string) {
boolean delimiterMatched = false;
char delimiter = '.';
for (int i = 0; i < string.length(); i++) {
char c = string.charAt(i);
if (!(c >= '0' && c <= '9' || c == delimiter)) {
// contains not number
return false;
}
if (c == delimiter) {
// delimiter matched twice
if (delimiterMatched) {
return false;
}
delimiterMatched = true;
}
}
// if matched delimiter once return true
return delimiterMatched;
}
Recursive solution
public static boolean isRealRecursive(String string) {
return isRealRecursive(string, 0, false);
}
private static boolean isRealRecursive(String string, int position, boolean delimiterMatched) {
char delimiter = '.';
if (position == string.length()) {
return delimiterMatched;
}
char c = string.charAt(position);
if (!(c >= '0' && c <= '9' || c == delimiter)) {
// contains not number
return false;
}
if (c == delimiter) {
// delimiter matched twice
if (delimiterMatched) {
return false;
}
delimiterMatched = true;
}
return isRealRecursive(string, position+1, delimiterMatched);
}
You need to use Regex. The regex to verify that whether a string holds a float number is:
^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$
Can anybody give me a tip on how to do this?
Starting with your existing recursive matcher for whole numbers, modify it and use it in another method to match the whole numbers in:
["+"|"-"]<whole-number>["."[<whole-number>]]
Hint: you will most likely need to change the existing method to return the index of that last character matched rather than just true / false. Think of the best way to encode "no match" in an integer result.
public static boolean isReal(String str) {
boolean real = true;
boolean sawDot = false;
char c;
for(int i = str.length() - 1; 0 <= i && real; i --) {
c = str.charAt(i);
if('-' == c || '+' == c) {
if(0 != i) {
real = false;
}
} else if('.' == c) {
if(!sawDot)
sawDot = true;
else
real = false;
} else {
if('0' > c || '9' < c)
real = false;
}
}
return real;
}

Categories