String70. Дана строка, содержащая латинские буквы и скобки трех видов: «()», «[]», «{}». Если скобки расставлены правильно (то есть каждой открывающей соответствует закрывающая скобка того же вида), то вывести число 0. В противном случае вывести или номер позиции, в которой расположена первая ошибочная скобка, или, если закрывающих скобок не хватает, число -1.
>Решение Pascal
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | program String70; var S,C:String; i,Num1,Num2,Num3,error:integer; begin Write('S: '); Readln(S); i:=1; error:=0; Num1:=0; Num2:=0; Num3:=0; while (i<=Length(S)) do begin if S[i]='(' then Num1:=Num1+1; if S[i]=')' then Num1:=Num1-1; if S[i]='[' then Num2:=Num2+1; if S[i]=']' then Num2:=Num2-1; if S[i]='{' then Num3:=Num3+1; if S[i]='}' then Num3:=Num3-1; if ((Num1<0) or (Num2<0) or (Num3<0)) and (error=0) then error:=i; inc(i); end; if error<>0 then Writeln(error) else if ((Num1>0) or (Num2>0) or (Num3>0)) then Writeln(-1) else Writeln(0); end. |
package str;
import java.util.Scanner;
public class Str {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String str = in.next();
if ((str.startsWith(«{«)&&str.endsWith(«}»))) {
System.out.println(«0»);
}
else {
System.out.println(«-1»);
}
}
}
program string70;
type
arrr=array[1..100] of string;
var
ar:arrr;
s:string;
pos2,pos1,i,num,num1,num2:integer;
begin
writeln(‘enter string’);
readln(s);
num:=0;num1:=0;num2:=0;
for i:=1 to length(s) do begin
if s[i]='(‘ then begin inc(num,1);pos1:=i; end;
if s[i]=’)’ then begin dec(num,1);pos2:=i; end;
if s[i]='{‘ then begin inc(num1,1);pos1:=i; end;
if s[i]=’}’ then begin dec(num1,1);pos2:=i; end;
if s[i]='[‘ then begin inc(num2,1);pos1:=i; end;
if s[i]=’]’ then begin dec(num2,1);pos2:=i; end;
if ((num=-1) or (num1=-1) or (num2=-1)) then begin writeln(‘pos=’,pos2);break; end;
end;
if ((num=0) and (num1=0) and (num2=0)) then writeln(‘0’);
if ((num=1) or (num1=1) or (num2=1) ) then writeln(‘-1’);
end.
добавьте пожалуйста на С++