-
-
Save key-moon/dec0bee566a47b9aa5d18c15cd0d4b4c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Collections.Generic; | |
using static System.Math; | |
class P | |
{ | |
static void Main() | |
{ | |
string s = Console.ReadLine(); | |
Console.WriteLine(Solve(s)); | |
} | |
//ソルバ +で区切り、それぞれの文字列の頭と終わりから空白を取り除き、それを頭からjoinしていく | |
static string Solve(string s) => s.Split('+').Select(x => x.Trim()).Aggregate((x, y) => Join(x, y)); | |
//sとtを連結 | |
static string Join(string s, string t) | |
{ | |
//s,tそれぞれの深さ | |
int sDepth = GetDepth(s); | |
int tDepth = GetDepth(t); | |
//深さが同じだったら単純に連結 | |
if (sDepth == tDepth) return s + t; | |
//深い方で浅い方を包む | |
if (sDepth > tDepth) return $"({PeelBracket(s)}{t})"; | |
if (sDepth < tDepth) return $"({s}{PeelBracket(t)})"; | |
//ここには来ない | |
throw new Exception(); | |
} | |
//一番外のカッコを剥く : "(()())" => "()()" | |
static string PeelBracket(string s) => s.Substring(1, s.Length - 2); | |
//カッコ列の深さを取得 | |
static int GetDepth(string s) | |
{ | |
int maxDepth = 0; | |
int currnetDepth = 0; | |
foreach (var c in s) | |
{ | |
if (c == '(') currnetDepth++; | |
else currnetDepth--; | |
maxDepth = Max(maxDepth, currnetDepth); | |
} | |
return maxDepth; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment