Leetcode: Valid parentheses
$begingroup$
https://leetcode.com/problems/valid-parentheses/
Given a string containing just the characters '(', ')', '{', '}', '['
and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets. Open
brackets must be closed in the correct order. Note that an empty
string is also considered valid.
Example 1:
Input: "()" Output: true Example 2:
Input: "(){}" Output: true Example 3:
Input: "(]" Output: false Example 4:
Input: "([)]" Output: false Example 5:
Input: "{}" Output: true
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace StackQuestions
{
[TestClass]
public class ValidParentheses
{
[TestMethod]
public void OpenOpenClosedClosedMixTest()
{
string input = "([)]";
bool result = IsValid(input);
Assert.IsFalse(result);
}
[TestMethod]
public void OnePairTest()
{
string input = "()";
bool result = IsValid(input);
Assert.IsTrue(result);
}
public bool IsValid(string s)
{
Stack<char> myStack = new Stack<char>();
foreach (var curr in s)
{
if (curr == '(')
{
myStack.Push(curr);
}
else if (curr == '[')
{
myStack.Push(curr);
}
else if (curr == '{')
{
myStack.Push(curr);
}
else if (curr == ')')
{
if (myStack.Count > 0)
{
var top = myStack.Pop();
if (top != '(')
{
return false;
}
}
else
{
return false;
}
}
else if (curr == ']')
{
if (myStack.Count > 0)
{
var top = myStack.Pop();
if (top != '[')
{
return false;
}
}
else
{
return false;
}
}
else if (curr == '}')
{
if (myStack.Count > 0)
{
var top = myStack.Pop();
if (top != '{')
{
return false;
}
}
else
{
return false;
}
}
}
return myStack.Count == 0;
}
}
}
Please review coding style as it was a job interview with 30 minutes to code. thanks!
c# programming-challenge interview-questions stack
$endgroup$
add a comment |
$begingroup$
https://leetcode.com/problems/valid-parentheses/
Given a string containing just the characters '(', ')', '{', '}', '['
and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets. Open
brackets must be closed in the correct order. Note that an empty
string is also considered valid.
Example 1:
Input: "()" Output: true Example 2:
Input: "(){}" Output: true Example 3:
Input: "(]" Output: false Example 4:
Input: "([)]" Output: false Example 5:
Input: "{}" Output: true
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace StackQuestions
{
[TestClass]
public class ValidParentheses
{
[TestMethod]
public void OpenOpenClosedClosedMixTest()
{
string input = "([)]";
bool result = IsValid(input);
Assert.IsFalse(result);
}
[TestMethod]
public void OnePairTest()
{
string input = "()";
bool result = IsValid(input);
Assert.IsTrue(result);
}
public bool IsValid(string s)
{
Stack<char> myStack = new Stack<char>();
foreach (var curr in s)
{
if (curr == '(')
{
myStack.Push(curr);
}
else if (curr == '[')
{
myStack.Push(curr);
}
else if (curr == '{')
{
myStack.Push(curr);
}
else if (curr == ')')
{
if (myStack.Count > 0)
{
var top = myStack.Pop();
if (top != '(')
{
return false;
}
}
else
{
return false;
}
}
else if (curr == ']')
{
if (myStack.Count > 0)
{
var top = myStack.Pop();
if (top != '[')
{
return false;
}
}
else
{
return false;
}
}
else if (curr == '}')
{
if (myStack.Count > 0)
{
var top = myStack.Pop();
if (top != '{')
{
return false;
}
}
else
{
return false;
}
}
}
return myStack.Count == 0;
}
}
}
Please review coding style as it was a job interview with 30 minutes to code. thanks!
c# programming-challenge interview-questions stack
$endgroup$
1
$begingroup$
@t3chb0t lol Sorry I forgot to write it down. thanks for the comment
$endgroup$
– Gilad
4 hours ago
add a comment |
$begingroup$
https://leetcode.com/problems/valid-parentheses/
Given a string containing just the characters '(', ')', '{', '}', '['
and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets. Open
brackets must be closed in the correct order. Note that an empty
string is also considered valid.
Example 1:
Input: "()" Output: true Example 2:
Input: "(){}" Output: true Example 3:
Input: "(]" Output: false Example 4:
Input: "([)]" Output: false Example 5:
Input: "{}" Output: true
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace StackQuestions
{
[TestClass]
public class ValidParentheses
{
[TestMethod]
public void OpenOpenClosedClosedMixTest()
{
string input = "([)]";
bool result = IsValid(input);
Assert.IsFalse(result);
}
[TestMethod]
public void OnePairTest()
{
string input = "()";
bool result = IsValid(input);
Assert.IsTrue(result);
}
public bool IsValid(string s)
{
Stack<char> myStack = new Stack<char>();
foreach (var curr in s)
{
if (curr == '(')
{
myStack.Push(curr);
}
else if (curr == '[')
{
myStack.Push(curr);
}
else if (curr == '{')
{
myStack.Push(curr);
}
else if (curr == ')')
{
if (myStack.Count > 0)
{
var top = myStack.Pop();
if (top != '(')
{
return false;
}
}
else
{
return false;
}
}
else if (curr == ']')
{
if (myStack.Count > 0)
{
var top = myStack.Pop();
if (top != '[')
{
return false;
}
}
else
{
return false;
}
}
else if (curr == '}')
{
if (myStack.Count > 0)
{
var top = myStack.Pop();
if (top != '{')
{
return false;
}
}
else
{
return false;
}
}
}
return myStack.Count == 0;
}
}
}
Please review coding style as it was a job interview with 30 minutes to code. thanks!
c# programming-challenge interview-questions stack
$endgroup$
https://leetcode.com/problems/valid-parentheses/
Given a string containing just the characters '(', ')', '{', '}', '['
and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets. Open
brackets must be closed in the correct order. Note that an empty
string is also considered valid.
Example 1:
Input: "()" Output: true Example 2:
Input: "(){}" Output: true Example 3:
Input: "(]" Output: false Example 4:
Input: "([)]" Output: false Example 5:
Input: "{}" Output: true
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace StackQuestions
{
[TestClass]
public class ValidParentheses
{
[TestMethod]
public void OpenOpenClosedClosedMixTest()
{
string input = "([)]";
bool result = IsValid(input);
Assert.IsFalse(result);
}
[TestMethod]
public void OnePairTest()
{
string input = "()";
bool result = IsValid(input);
Assert.IsTrue(result);
}
public bool IsValid(string s)
{
Stack<char> myStack = new Stack<char>();
foreach (var curr in s)
{
if (curr == '(')
{
myStack.Push(curr);
}
else if (curr == '[')
{
myStack.Push(curr);
}
else if (curr == '{')
{
myStack.Push(curr);
}
else if (curr == ')')
{
if (myStack.Count > 0)
{
var top = myStack.Pop();
if (top != '(')
{
return false;
}
}
else
{
return false;
}
}
else if (curr == ']')
{
if (myStack.Count > 0)
{
var top = myStack.Pop();
if (top != '[')
{
return false;
}
}
else
{
return false;
}
}
else if (curr == '}')
{
if (myStack.Count > 0)
{
var top = myStack.Pop();
if (top != '{')
{
return false;
}
}
else
{
return false;
}
}
}
return myStack.Count == 0;
}
}
}
Please review coding style as it was a job interview with 30 minutes to code. thanks!
c# programming-challenge interview-questions stack
c# programming-challenge interview-questions stack
edited 14 mins ago
user673679
2,8851926
2,8851926
asked 5 hours ago
GiladGilad
1,29431526
1,29431526
1
$begingroup$
@t3chb0t lol Sorry I forgot to write it down. thanks for the comment
$endgroup$
– Gilad
4 hours ago
add a comment |
1
$begingroup$
@t3chb0t lol Sorry I forgot to write it down. thanks for the comment
$endgroup$
– Gilad
4 hours ago
1
1
$begingroup$
@t3chb0t lol Sorry I forgot to write it down. thanks for the comment
$endgroup$
– Gilad
4 hours ago
$begingroup$
@t3chb0t lol Sorry I forgot to write it down. thanks for the comment
$endgroup$
– Gilad
4 hours ago
add a comment |
2 Answers
2
active
oldest
votes
$begingroup$
You get the job done in 30 minutes and the use of a stack is the way to go, so that's a good start. In my opinion you're writing a little too much (repetitive) code and it could be a lot easier to read if you use a switch
-statement instead:
public bool IsValidReview(string s)
{
Stack<char> endings = new Stack<char>();
foreach (var curr in s)
{
switch (curr)
{
case '(':
endings.Push(')');
break;
case '[':
endings.Push(']');
break;
case '{':
endings.Push('}');
break;
case ')':
case ']':
case '}':
if (endings.Count == 0 || endings.Pop() != curr)
return false;
break;
}
}
return endings.Count == 0;
}
Here the corresponding ending parenthesis is pushed to the stack instead of the starting one, which makes it easier to check when the ending shows up.
The name myStack
doesn't say much, so I have changed it to something more meaningful in the context.
$endgroup$
$begingroup$
Cool thanks I was wondering if switch case is the way to go or not
$endgroup$
– Gilad
1 hour ago
add a comment |
$begingroup$
A couple of small things to add:
Maybe not applicable to a timed interview, but inline documentation (
///
) on public members is always nice, and would help to explain the otherwise vagueIsValid
method name.I'd want to throw an exception if any other character is encountered, since the behaviour is undefined and undocumented. The spec says to assume only
(){}
will appear in the string, which means anyone using it incorrectly (by including such characters) should be informed (maybe they assume it handles<>
as well?). If a customer were to depend upon this (undocumented) behaviour of just ignoring such characters, you'd have another undocumented 'feature' to maintain in future (or else an unhappy customer).Any reason the method isn't
static
? Conceptual benefits aside, making it static would make it clear that it's not messing with any state, and makes it easier to use.That's a very limited set of test-cases: you don't test for
{}
at all.
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212445%2fleetcode-valid-parentheses%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
You get the job done in 30 minutes and the use of a stack is the way to go, so that's a good start. In my opinion you're writing a little too much (repetitive) code and it could be a lot easier to read if you use a switch
-statement instead:
public bool IsValidReview(string s)
{
Stack<char> endings = new Stack<char>();
foreach (var curr in s)
{
switch (curr)
{
case '(':
endings.Push(')');
break;
case '[':
endings.Push(']');
break;
case '{':
endings.Push('}');
break;
case ')':
case ']':
case '}':
if (endings.Count == 0 || endings.Pop() != curr)
return false;
break;
}
}
return endings.Count == 0;
}
Here the corresponding ending parenthesis is pushed to the stack instead of the starting one, which makes it easier to check when the ending shows up.
The name myStack
doesn't say much, so I have changed it to something more meaningful in the context.
$endgroup$
$begingroup$
Cool thanks I was wondering if switch case is the way to go or not
$endgroup$
– Gilad
1 hour ago
add a comment |
$begingroup$
You get the job done in 30 minutes and the use of a stack is the way to go, so that's a good start. In my opinion you're writing a little too much (repetitive) code and it could be a lot easier to read if you use a switch
-statement instead:
public bool IsValidReview(string s)
{
Stack<char> endings = new Stack<char>();
foreach (var curr in s)
{
switch (curr)
{
case '(':
endings.Push(')');
break;
case '[':
endings.Push(']');
break;
case '{':
endings.Push('}');
break;
case ')':
case ']':
case '}':
if (endings.Count == 0 || endings.Pop() != curr)
return false;
break;
}
}
return endings.Count == 0;
}
Here the corresponding ending parenthesis is pushed to the stack instead of the starting one, which makes it easier to check when the ending shows up.
The name myStack
doesn't say much, so I have changed it to something more meaningful in the context.
$endgroup$
$begingroup$
Cool thanks I was wondering if switch case is the way to go or not
$endgroup$
– Gilad
1 hour ago
add a comment |
$begingroup$
You get the job done in 30 minutes and the use of a stack is the way to go, so that's a good start. In my opinion you're writing a little too much (repetitive) code and it could be a lot easier to read if you use a switch
-statement instead:
public bool IsValidReview(string s)
{
Stack<char> endings = new Stack<char>();
foreach (var curr in s)
{
switch (curr)
{
case '(':
endings.Push(')');
break;
case '[':
endings.Push(']');
break;
case '{':
endings.Push('}');
break;
case ')':
case ']':
case '}':
if (endings.Count == 0 || endings.Pop() != curr)
return false;
break;
}
}
return endings.Count == 0;
}
Here the corresponding ending parenthesis is pushed to the stack instead of the starting one, which makes it easier to check when the ending shows up.
The name myStack
doesn't say much, so I have changed it to something more meaningful in the context.
$endgroup$
You get the job done in 30 minutes and the use of a stack is the way to go, so that's a good start. In my opinion you're writing a little too much (repetitive) code and it could be a lot easier to read if you use a switch
-statement instead:
public bool IsValidReview(string s)
{
Stack<char> endings = new Stack<char>();
foreach (var curr in s)
{
switch (curr)
{
case '(':
endings.Push(')');
break;
case '[':
endings.Push(']');
break;
case '{':
endings.Push('}');
break;
case ')':
case ']':
case '}':
if (endings.Count == 0 || endings.Pop() != curr)
return false;
break;
}
}
return endings.Count == 0;
}
Here the corresponding ending parenthesis is pushed to the stack instead of the starting one, which makes it easier to check when the ending shows up.
The name myStack
doesn't say much, so I have changed it to something more meaningful in the context.
answered 1 hour ago
Henrik HansenHenrik Hansen
6,9701824
6,9701824
$begingroup$
Cool thanks I was wondering if switch case is the way to go or not
$endgroup$
– Gilad
1 hour ago
add a comment |
$begingroup$
Cool thanks I was wondering if switch case is the way to go or not
$endgroup$
– Gilad
1 hour ago
$begingroup$
Cool thanks I was wondering if switch case is the way to go or not
$endgroup$
– Gilad
1 hour ago
$begingroup$
Cool thanks I was wondering if switch case is the way to go or not
$endgroup$
– Gilad
1 hour ago
add a comment |
$begingroup$
A couple of small things to add:
Maybe not applicable to a timed interview, but inline documentation (
///
) on public members is always nice, and would help to explain the otherwise vagueIsValid
method name.I'd want to throw an exception if any other character is encountered, since the behaviour is undefined and undocumented. The spec says to assume only
(){}
will appear in the string, which means anyone using it incorrectly (by including such characters) should be informed (maybe they assume it handles<>
as well?). If a customer were to depend upon this (undocumented) behaviour of just ignoring such characters, you'd have another undocumented 'feature' to maintain in future (or else an unhappy customer).Any reason the method isn't
static
? Conceptual benefits aside, making it static would make it clear that it's not messing with any state, and makes it easier to use.That's a very limited set of test-cases: you don't test for
{}
at all.
$endgroup$
add a comment |
$begingroup$
A couple of small things to add:
Maybe not applicable to a timed interview, but inline documentation (
///
) on public members is always nice, and would help to explain the otherwise vagueIsValid
method name.I'd want to throw an exception if any other character is encountered, since the behaviour is undefined and undocumented. The spec says to assume only
(){}
will appear in the string, which means anyone using it incorrectly (by including such characters) should be informed (maybe they assume it handles<>
as well?). If a customer were to depend upon this (undocumented) behaviour of just ignoring such characters, you'd have another undocumented 'feature' to maintain in future (or else an unhappy customer).Any reason the method isn't
static
? Conceptual benefits aside, making it static would make it clear that it's not messing with any state, and makes it easier to use.That's a very limited set of test-cases: you don't test for
{}
at all.
$endgroup$
add a comment |
$begingroup$
A couple of small things to add:
Maybe not applicable to a timed interview, but inline documentation (
///
) on public members is always nice, and would help to explain the otherwise vagueIsValid
method name.I'd want to throw an exception if any other character is encountered, since the behaviour is undefined and undocumented. The spec says to assume only
(){}
will appear in the string, which means anyone using it incorrectly (by including such characters) should be informed (maybe they assume it handles<>
as well?). If a customer were to depend upon this (undocumented) behaviour of just ignoring such characters, you'd have another undocumented 'feature' to maintain in future (or else an unhappy customer).Any reason the method isn't
static
? Conceptual benefits aside, making it static would make it clear that it's not messing with any state, and makes it easier to use.That's a very limited set of test-cases: you don't test for
{}
at all.
$endgroup$
A couple of small things to add:
Maybe not applicable to a timed interview, but inline documentation (
///
) on public members is always nice, and would help to explain the otherwise vagueIsValid
method name.I'd want to throw an exception if any other character is encountered, since the behaviour is undefined and undocumented. The spec says to assume only
(){}
will appear in the string, which means anyone using it incorrectly (by including such characters) should be informed (maybe they assume it handles<>
as well?). If a customer were to depend upon this (undocumented) behaviour of just ignoring such characters, you'd have another undocumented 'feature' to maintain in future (or else an unhappy customer).Any reason the method isn't
static
? Conceptual benefits aside, making it static would make it clear that it's not messing with any state, and makes it easier to use.That's a very limited set of test-cases: you don't test for
{}
at all.
answered 44 mins ago
VisualMelonVisualMelon
3,2141023
3,2141023
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f212445%2fleetcode-valid-parentheses%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
$begingroup$
@t3chb0t lol Sorry I forgot to write it down. thanks for the comment
$endgroup$
– Gilad
4 hours ago