Day8-9
This commit is contained in:
11
20. Valid Parentheses/20. Valid Parentheses.csproj
Normal file
11
20. Valid Parentheses/20. Valid Parentheses.csproj
Normal file
@@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<RootNamespace>_20._Valid_Parentheses</RootNamespace>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
9
20. Valid Parentheses/Program.cs
Normal file
9
20. Valid Parentheses/Program.cs
Normal file
@@ -0,0 +1,9 @@
|
||||
namespace _20._Valid_Parentheses;
|
||||
|
||||
internal class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
Console.WriteLine(new Solution().IsValid("([)]"));
|
||||
}
|
||||
}
|
||||
68
20. Valid Parentheses/Solution.cs
Normal file
68
20. Valid Parentheses/Solution.cs
Normal file
@@ -0,0 +1,68 @@
|
||||
using System.Text;
|
||||
|
||||
namespace _20._Valid_Parentheses;
|
||||
|
||||
public class Solution
|
||||
{
|
||||
public bool IsValid(string s)
|
||||
{
|
||||
StringBuilder sb = new StringBuilder(s);
|
||||
if (sb.Length == 0)
|
||||
return true;
|
||||
if (sb.Length % 2 == 1)
|
||||
return false;
|
||||
while(sb.Length > 0)
|
||||
{
|
||||
char ch = sb[0];
|
||||
if ("({[".Contains(ch) == false)
|
||||
return false;
|
||||
char need = ch switch
|
||||
{
|
||||
'(' => ')',
|
||||
'{' => '}',
|
||||
'[' => ']',
|
||||
_ => '\0'
|
||||
};
|
||||
int count1 = 0;// ()
|
||||
int count2 = 0;// {}
|
||||
int count3 = 0;// []
|
||||
bool succes = false;
|
||||
for(int i = 1; i < sb.Length; i++)
|
||||
{
|
||||
char c = sb[i];
|
||||
if (count1 == 0 && count2 == 0 && count3 == 0 && c == need)
|
||||
{
|
||||
sb.Remove(i, 1).Remove(0, 1);
|
||||
succes = true;
|
||||
break;
|
||||
}
|
||||
switch (c)
|
||||
{
|
||||
case '(':
|
||||
count1++;
|
||||
break;
|
||||
case ')':
|
||||
count1--;
|
||||
break;
|
||||
|
||||
case '{':
|
||||
count2++;
|
||||
break;
|
||||
case '}':
|
||||
count2--;
|
||||
break;
|
||||
|
||||
case '[':
|
||||
count3++;
|
||||
break;
|
||||
case ']':
|
||||
count3--;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(succes == false)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user