kathy
BAN USER* 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));
?>
function reverse($arr, $k){
$midvalue = floor($k/2);
for($i = 0; $i <= $midvalue; $i++){
$lasindex = $k - $i -1;
if($arr[$i] < $arr[$lasindex]){
continue;
}
$temp = $arr[$i];
$arr[$i] = $arr[$lasindex];
$arr[$lasindex] = $temp;
}
return $arr;
}
$arr = [2,3,1,5,4];
$res = reverse($arr, 3);
print "[". implode(",",$res) ."]";
Best Case is n;
Worst Case is n power 2
function getrepetitionPattern($str){
$arr = str_split($str);
$len = count($arr);
$pattern[0] = $arr[0];
$i = 0; //pattern index
$r = 1; //array init index
$j = 1; //array pointer
$n = 1;
while($j < $len){
if($arr[$j] == $pattern[$i]){
$j++; $i++;
if(count($pattern) == $i ) {
$i = 0;
$n++; //increase patter count
}
}else{
$pattern[] = $arr[$r];
$r ++; $j = $r;
$i = 0;
$n = 1;
}
}
print $n."".implode("",$pattern)."<br/><br/>";
}
$str1 = "abababab";
$str2 = "xxxxxxxk";
$str3 = "aabbaaabbaa";
getrepetitionPattern($str1);
echo '<br/>';
getrepetitionPattern($str2);
echo '<br/>';
getrepetitionPattern($str3);
Using memorized index array to second occurrence number.
* loop from last number
-- Case 1, if value is greater than mid. look left side to swap. And chang memorized value of
-- Case 2, if value is mid, look to left or right to swap, if swap position is less than, swap value
-- Case 3, if value id less than mid, cannot swap. Do validation
* Best and Worst Case : O(n)
- kathy December 03, 2019