C++刷题——括号配对问题

来源:互联网 发布:网络冗余设计 编辑:程序博客网 时间:2024/05/13 22:13

题目:

S = s1 s2...s2n 是一个符合格式的括号的字符串,S能按下面两种方式编码:
P编码:编码是一个整数序列P = p1 p2...pn,pi是第i个右括号之前的左括号的数目。
W编码:编码是一个整数序列W= p1 p2...pn,wi是第i个右括号的编码值,它等于这个右括号到与之匹配的左括号的下标。


解题思路:将P转换成S,再将S转换成W。


源代码:

#include <iostream>
using namespace std;
void display1(char a[], int n);
void display2(int a[], int n);
void conv(char a[], int n);

int main ()
{
 int n=6;
 char p[6] ={4,5,6,6,6,6};
 
 conv(p, 2*n);
 
 return 0;

}

void display1 (char a[], int n)
{
 for (int i=0; i<n; i++)
  cout << a[i]<<"\t";
 cout <<endl;
}
void display2 (int a[], int n)
{
 for (int i=0; i<n; i++)
  cout << a[i]<<"\t";
 cout <<endl;
}


void conv(char p[], int n)
{
 char s[n];
 int w[n/2];
 int posits=0, countL=0, positw=0;
 
 for (int i=0; i<n/2; i++)    //convert P[n/2] to s[n]
 {
  while (posits < n)
  {
   if (countL < p[i])
   {
    s[posits]= '(';
    countL ++;
    posits ++;
   }
   else
   {
    s[posits] =')';
    posits ++;
    break;
   }
  }
 }
 cout<<"The original array is: \n";
 display1 (s,n);
 
 //convert s[n] to w[n/2]
 while (positw < n/2)
 {
  for (int i=p[positw]; i<n; i++)
  {
   if (s[i] == ')')
   {
    for (int j=i-1; j>=0; j--)
     if (s[j] == '(' )
     {
      w[positw] = j;
      s[j] = ' ';
      positw ++;
      cout<<"The "<<positw<<"th ( of p is "<<j<<"\n";
      break;
     }
   }
  }
 }
 cout <<"The array w is: \n";
 display2(w, n/2); 
}
  


0 0
原创粉丝点击