Advertisement
ogv

Untitled

ogv
Sep 3rd, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. public class Solution
  2. {
  3. public IList<string> RemoveInvalidParentheses(string s)
  4. {
  5. var results = new HashSet<string>();
  6. Enumerate(s, results);
  7. return results.ToList();
  8. }
  9.  
  10. private void Enumerate(string s, ISet<string> results)
  11. {
  12. int balance = 0;
  13. for (int i = 0; i < s.Length; i++)
  14. {
  15. if (s[i] == '(') balance++;
  16. else if (s[i] == ')') balance--;
  17.  
  18. if (balance < 0)
  19. {
  20. for (int j = 0; j <= i; j++)
  21. {
  22. if (s[j] == ')')
  23. {
  24. string newPrefix = s.Substring(0, i + 1);
  25. newPrefix = newPrefix.Remove(j, 1);
  26. string newS;
  27. if (i < s.Length - 1){
  28. newS = newPrefix + s.Substring(i + 1, s.Length - i - 1);
  29. }
  30. else {
  31. newS = newPrefix;
  32. }
  33. Enumerate(newS, results);
  34. }
  35. }
  36. return;
  37. }
  38. }
  39.  
  40. if (balance == 0)
  41. {
  42. results.Add(s);
  43. }
  44. }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement