簡體   English   中英

Java平衡字符串不使用堆棧

[英]Java Balanced String not using stack

我需要檢查給定的字符串是否平衡。 這與帶有平衡括號的任務類似。

程序

請讓我知道這是否適合您。

嘗試這個

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錯了嗎? 和括號一樣嗎?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM