Facebook Interview Question
Software EngineersCountry: United States
Interview Type: In-Person
* handle with stack, To simplify stack, validation only double quote and open and close only. Not included (colon) and (comma) validation
* if double quote
- if top stack is not"double quote", add to stack
- if top stack is double quote, take out top from stack
* if open {
-if top stack is double quote, error
- else add to stack
* if close "}"
- if stack is empty, error
- if top stack is double quote, error
- if top stack is not open "{", error
- if top stack is open "{", take out top from stack
<?php
function jsonValidator($str){
$arr = str_split($str);
$stack = [];
$count = count($arr);
$i = 0;
//$sc = 0;
while($i < $count){
$sc = count($stack) -1;
if($arr[0] != "{"){
return false;
}
if($arr[$i] == '"'){
if($stack[$sc] == '"'){
array_pop($stack);
}else{
array_push($stack, $arr[$i]);
}
}else if($arr[$i] == "{"){
if($sc > 0 &&$stack[$sc] == '"'){
return false;
}else{
array_push($stack, $arr[$i]);
}
}else if($arr[$i] == "}"){
if($sc < 0){
return false;
}else if($stack[$sc] == '"'){
return false;
}else if($stack[$sc] != '{'){
return false;
}else{
array_pop($stack);
}
}
$i++;
}
if(count($stack) != 0){
return false;
}
return true;
}
$str = '{"name" : "Jone", "gender" : "female", "school" : { "hight", "school"}}';
var_dump(jsonValidator($str));
?>
{
- xzhan211@binghamton.edu July 22, 2019key1 : value1,
key2 : {key2_1: value2_1},
key3 : [{key3_1: value3_1}, {key3_2: value3_2}]
}
recursion