image.png

    1. import java.util.Stack;
    2. public class Practice
    3. {
    4. public static void main(String[] args)
    5. {
    6. String a = "[()]{}{[()]}";
    7. String b = "[(])";
    8. System.out.println(isLegal(a));
    9. System.out.println(isLegal(b));
    10. }
    11. public static boolean isLegal(String string)
    12. {
    13. Stack<Character> stack = new Stack<Character>();
    14. for (int i = 0; i < string.length(); ++i)
    15. {
    16. char c = string.charAt(i);
    17. if (c == '[' || c == '(' || c == '{')
    18. {
    19. stack.push(c);
    20. }
    21. else if (c == ')')
    22. {
    23. char temp = stack.pop();
    24. if (temp != '(')
    25. return false;
    26. }
    27. else if (c == ']')
    28. {
    29. char temp = stack.pop();
    30. if (temp != '[')
    31. return false;
    32. }
    33. else if (c == '}')
    34. {
    35. char temp = stack.pop();
    36. if (temp != '{')
    37. return false;
    38. }
    39. }
    40. return true;
    41. }
    42. }

    image.png

    1. import java.util.Stack;
    2. public class Practice
    3. {
    4. public static void main(String[] args)
    5. {
    6. String s = "1 + 2 ) * 3 - 4 ) * 5 - 6 ) ) )";
    7. Stack<String> stack = new Stack<>();
    8. Stack<String> num = new Stack<>();
    9. String[] strings = s.split(" ");
    10. for (int i = 0; i < strings.length; ++i)
    11. {
    12. if (strings[i].equals("+") || strings[i].equals("-") || strings[i].equals("*") || strings[i].equals("/"))
    13. {
    14. stack.push(strings[i]);
    15. }
    16. else if (strings[i].equals(")"))
    17. {
    18. String string = "(";
    19. String a = num.pop();
    20. String b = num.pop();
    21. string += b + stack.pop() + a + ")";
    22. num.push(string);
    23. }
    24. else
    25. num.push(strings[i]);
    26. }
    27. System.out.println(num.pop());
    28. }
    29. }