Parentheses Matching

题目1 : Parentheses Matching

时间限制:10000ms

单点时限:1000ms

内存限制:256MB

描述

Given a string of balanced parentheses output all the matching pairs.

输入

A string consisting of only parentheses '(' and ')'. The parentheses are balanced and the length of the string is no more than 100000.

输出

For each pair of matched parentheses output their positions in the string.

样例输入

(())()()

样例输出

1 4  
2 3  
5 6  
7 8

import java.util.Scanner;
import java.util.Stack;

public class Main_228 {

    Main_228(){
        Scanner cin = new Scanner(System.in);
        char[] a = cin.next().toCharArray();
        Stack<Integer>  stack = new Stack<>();
        int [] ans = new int[a.length];
        for(int i = 0; i < a.length ; i ++){
            if(a[i] == '('){
                stack.push(i);
            }
            else{
                int left = stack.pop();
                ans[left] = i;
            }
        }
        for(int i = 0; i < a.length ; i ++){
            if(a[i] == '('){
                System.out.println((i +1) + " " + (ans[i] + 1));
            }
        }
    }
public static void main(String[]args){
    new Main_228();
}
}

猜你喜欢

转载自blog.csdn.net/weixin_38970751/article/details/85274371