简体   繁体   中英

Java Balanced String not using stack

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;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM