Ibibo Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Written Test
function findSinglePairOfParenthesis(string n) {
if (n == null) return null;
// Go to the end of the string
while (*n != '\0') n++;
if (n == '\0') return null;
// Find closing bracket
while (*n != ')') n--;
// Terminate the string right in place
n++;
*n = '\0';
// Find opening bracket
while (*n != '(') n--;
return n;
}
Good Answer provided by Sunny. Very near solution in C#
IEnumerable<string> GetValue(string val)
{
while (val.Length != 0)
{
if(val.Substring(0,1) == "(")
{
while(val.Substring(0,1) != ")")
{
yield return val.Substring(0, 1);
val = val.Substring(1);
}
yield return val.Substring(0, 1);
}
val = val.Substring(1);
}
yield return string.Empty;
}
Here's python version without explicit variables
def find_start(input_string):
if input_string.startswith("("):
return input_string
return find_start(input_string[1:])
def find_end(input_string):
if input_string.endswith(")"):
return input_string
return find_end(input_string[:-1])
def in_parenthesis(input_string):
return find_end(find_start(input_string))
def printInsideParens(s):
if s[0] == '(':
print '(',
printUntilOutside(s[1:])
else:
printInsideParens(s[1:])
def printUntilOutside(s):
if s[0] != ')':
print s[0],
printUntilOutside(s[1:])
else:
print ')'
//IN JAVA
//finding the string within the given parenthesis without using variables
public class Parenthesis {
public static void main(String[] args) {
System.out.println(parenthesis("k(us)hal"));
}
public static String parenthesis(String input) {
if (!Character.toString(input.charAt(0)).equals("(")) {
return parenthesis(input.substring(1));
} else if (!Character.toString(input.charAt(input.length() - 1))
.equals(")")) {
return parenthesis(input.substring(0, input.length() - 1));
} else {
return input;
}
}
}
- Sunny July 03, 2014