diff --git a/src/Algorithms/s0001_two_sum/Solution.php b/src/Algorithms/s0001_two_sum/Solution.php index f368863..7ef39e1 100644 --- a/src/Algorithms/s0001_two_sum/Solution.php +++ b/src/Algorithms/s0001_two_sum/Solution.php @@ -1,3 +1,9 @@ +val : 0; diff --git a/src/Algorithms/s0003_longest_substring_without_repeating_characters/Solution.php b/src/Algorithms/s0003_longest_substring_without_repeating_characters/Solution.php index f131766..6322784 100644 --- a/src/Algorithms/s0003_longest_substring_without_repeating_characters/Solution.php +++ b/src/Algorithms/s0003_longest_substring_without_repeating_characters/Solution.php @@ -1,3 +1,9 @@ +$nums2[$q]) || $p==count($nums1)) - { - $array[$i]=$nums2[$q]; + } else if (($p < count($nums1) && $q < count($nums2) && $nums1[$p] > $nums2[$q]) || $p == count($nums1)) { + $array[$i] = $nums2[$q]; $q++; } } - if (intval(count($array) % 2)==0) - { - return doubleval($array[count($array) / 2] + $array[(count($array) / 2) - 1])/2; - } - else - { + if (intval(count($array) % 2) == 0) { + return doubleval($array[count($array) / 2] + $array[(count($array) / 2) - 1]) / 2; + } else { return doubleval($array[count($array) / 2]); } } diff --git a/src/Algorithms/s0005_longest_palindromic_substring/Solution.php b/src/Algorithms/s0005_longest_palindromic_substring/Solution.php index ca2d331..cc904be 100644 --- a/src/Algorithms/s0005_longest_palindromic_substring/Solution.php +++ b/src/Algorithms/s0005_longest_palindromic_substring/Solution.php @@ -1,3 +1,10 @@ +=0;$i--){ + } + $dp = array_fill(0, strlen($s), array_fill(0, strlen($s), false)); + $longestPalindromeStart = 0; + $longestPalindromeLength = 1; + for ($i = strlen($s) - 1; $i >= 0; $i--) { $dp[$i][$i] = true; //single character is a palindrome so making it true - for($j=$i+1;$j $longestPalindromeLength) { // update the length if greater than previous $longestPalindromeLength = $j - $i + 1; $longestPalindromeStart = $i; @@ -23,6 +31,6 @@ function longestPalindrome($s) { } } // return the substring using starting and ending index - return substr($s, $longestPalindromeStart,$longestPalindromeLength); + return substr($s, $longestPalindromeStart, $longestPalindromeLength); } -} \ No newline at end of file +} diff --git a/src/Algorithms/s0006_zigzag_conversion/Solution.php b/src/Algorithms/s0006_zigzag_conversion/Solution.php index 6a3e81a..cd2db02 100644 --- a/src/Algorithms/s0006_zigzag_conversion/Solution.php +++ b/src/Algorithms/s0006_zigzag_conversion/Solution.php @@ -1,3 +1,7 @@ + 2147483647 || intval($rev) < -2147483647 ) return 0; - return intval($rev); + if (intval($rev) > 2147483647 || intval($rev) < -2147483647) return 0; + return intval($rev); } } diff --git a/src/Algorithms/s0008_string_to_integer_atoi/Solution.php b/src/Algorithms/s0008_string_to_integer_atoi/Solution.php index 85d34c6..baa73a7 100644 --- a/src/Algorithms/s0008_string_to_integer_atoi/Solution.php +++ b/src/Algorithms/s0008_string_to_integer_atoi/Solution.php @@ -1,3 +1,7 @@ + 9) - break; - if ($ans > intval(2147483647 / 10) - || ($ans == intval(2147483647 / 10) && (2147483647 % 10) < $tmp)) { - return $sign == 1 ? 2147483647 : -2147483648; - } else - $ans = $ans * 10 + $tmp; - } - return $sign * $ans; + if (trim($str) == '') + return 0; + $str = trim($str); + $i = 0; + $ans = 0; + $sign = 1; + $len = strlen($str); + if ($str[$i] == '-' || $str[$i] == '+') + $sign = $str[$i++] == '+' ? 1 : -1; + for (; $i < $len; ++$i) { + $tmp = ord($str[$i]) - ord('0'); + if ($tmp < 0 || $tmp > 9) + break; + if ($ans > intval(2147483647 / 10) + || ($ans == intval(2147483647 / 10) && (2147483647 % 10) < $tmp)) { + return $sign == 1 ? 2147483647 : -2147483648; + } else + $ans = $ans * 10 + $tmp; + } + return $sign * $ans; } } diff --git a/src/Algorithms/s0009_palindrome_number/Solution.php b/src/Algorithms/s0009_palindrome_number/Solution.php index 545b004..ca6ad22 100644 --- a/src/Algorithms/s0009_palindrome_number/Solution.php +++ b/src/Algorithms/s0009_palindrome_number/Solution.php @@ -1,3 +1,7 @@ +0; $x= intval($x / 10)){ + if ($x < 0) return false; + $i = 0; + $rev = 0; + $ori = $x; + for ($i = 10; $x > 0; $x = intval($x / 10)) { $rev *= 10; $rev += $x % $i; } - return $rev==$ori; + return $rev == $ori; } -} \ No newline at end of file +} diff --git a/src/Algorithms/s0010_regular_expression_matching/Solution.php b/src/Algorithms/s0010_regular_expression_matching/Solution.php index 8f6322f..b643927 100644 --- a/src/Algorithms/s0010_regular_expression_matching/Solution.php +++ b/src/Algorithms/s0010_regular_expression_matching/Solution.php @@ -1,3 +1,9 @@ += 0; $i--){ - for ($j = strlen($p) - 1; $j >= 0; $j--){ + for ($i = strlen($s); $i >= 0; $i--) { + for ($j = strlen($p) - 1; $j >= 0; $j--) { $first_match = ($i < strlen($s) && - ($p[$j] == $s[$i] || - $p[$j] == '.')); - if ($j + 1 < strlen($p) && $p[$j+1] == '*'){ - $dp[$i][$j] = $dp[$i][$j+2] || $first_match && $dp[$i+1][$j]; + ($p[$j] == $s[$i] || + $p[$j] == '.')); + if ($j + 1 < strlen($p) && $p[$j + 1] == '*') { + $dp[$i][$j] = $dp[$i][$j + 2] || $first_match && $dp[$i + 1][$j]; } else { - $dp[$i][$j] = $first_match && $dp[$i+1][$j+1]; + $dp[$i][$j] = $first_match && $dp[$i + 1][$j + 1]; } } } return $dp[0][0]; } -} \ No newline at end of file +} diff --git a/src/Algorithms/s0011_container_with_most_water/Solution.php b/src/Algorithms/s0011_container_with_most_water/Solution.php index 35b310c..9442426 100644 --- a/src/Algorithms/s0011_container_with_most_water/Solution.php +++ b/src/Algorithms/s0011_container_with_most_water/Solution.php @@ -1,3 +1,5 @@ + 0){ - $repeats = intval($num/$values[$i]); - if($repeats >= 1){ - while($repeats != 0){ + + while ($num > 0) { + $repeats = intval($num / $values[$i]); + if ($repeats >= 1) { + while ($repeats != 0) { $sb .= $roman[$i]; $repeats--; } - $num = $num - intval($num/$values[$i])*$values[$i]; + $num = $num - intval($num / $values[$i]) * $values[$i]; } $i++; } diff --git a/src/Algorithms/s0013_roman_to_integer/Solution.php b/src/Algorithms/s0013_roman_to_integer/Solution.php index 0acda30..94e1136 100644 --- a/src/Algorithms/s0013_roman_to_integer/Solution.php +++ b/src/Algorithms/s0013_roman_to_integer/Solution.php @@ -1,3 +1,5 @@ + 1, - 'V' => 5, - 'X' => 10, - 'L' => 50, - 'C' => 100, - 'D' => 500, - 'M' => 1000]; - + 'I' => 1, + 'V' => 5, + 'X' => 10, + 'L' => 50, + 'C' => 100, + 'D' => 500, + 'M' => 1000]; + $result = 0; - for($i = 0; $i < strlen($s); $i++) { + for ($i = 0; $i < strlen($s); $i++) { $first = $map[$s[$i]]; - if($i <= strlen($s) - 2) { + if ($i <= strlen($s) - 2) { $second = $map[$s[$i + 1]]; - if($second > $first) { + if ($second > $first) { $result += $second - $first; $i++; - } - else { + } else { $result += $first; } - } - else + } else $result += $first; } - + return $result; } } \ No newline at end of file diff --git a/src/Algorithms/s0014_longest_common_prefix/Solution.php b/src/Algorithms/s0014_longest_common_prefix/Solution.php index 9779c7f..90010ed 100644 --- a/src/Algorithms/s0014_longest_common_prefix/Solution.php +++ b/src/Algorithms/s0014_longest_common_prefix/Solution.php @@ -1,3 +1,5 @@ + $target) { $k--; } else { $j++; } } - while ($i < $n - 2 && $nums[$i] == $nums[++$i]); + while ($i < $n - 2 && $nums[$i] == $nums[++$i]) ; } return $res; } diff --git a/src/Algorithms/s0016_3sum_closest/Solution.php b/src/Algorithms/s0016_3sum_closest/Solution.php index d7c8856..b0fa7f5 100644 --- a/src/Algorithms/s0016_3sum_closest/Solution.php +++ b/src/Algorithms/s0016_3sum_closest/Solution.php @@ -1,3 +1,5 @@ +phone = [ - "2" => "abc", - "3" => "def", - "4" => "ghi", - "5" => "jkl", - "6" => "mno", - "7" => "pqrs", - "8" => "tuv", - "9" => "wxyz" - ]; - $this->output = []; - } +output, $combination); +class Solution { + public function __construct() { + $this->phone = [ + "2" => "abc", + "3" => "def", + "4" => "ghi", + "5" => "jkl", + "6" => "mno", + "7" => "pqrs", + "8" => "tuv", + "9" => "wxyz" + ]; + $this->output = []; } - // if there are still digits to check - else { - // iterate over all letters which map - // the next available digit - $digit = substr($next_digits, 0, 1); - $letters = $this->phone[$digit]; - for ($i = 0; $i < strlen($letters); $i++) { - $letter = substr($this->phone[$digit], $i, 1); - // append the current letter to the combination - // and proceed to the next digits - self::backtrack($combination . $letter, substr($next_digits, 1)); - } + + function backtrack($combination, $next_digits) { + // if there is no more digits to check + if (strlen($next_digits) == 0) { + // the combination is done + array_push($this->output, $combination); + } // if there are still digits to check + else { + // iterate over all letters which map + // the next available digit + $digit = substr($next_digits, 0, 1); + $letters = $this->phone[$digit]; + for ($i = 0; $i < strlen($letters); $i++) { + $letter = substr($this->phone[$digit], $i, 1); + // append the current letter to the combination + // and proceed to the next digits + self::backtrack($combination . $letter, substr($next_digits, 1)); + } + } } - } + /** * @param String $digits * @return String[] */ function letterCombinations($digits) { if (strlen($digits) != 0) - self::backtrack("", $digits); - return $this->output; + self::backtrack("", $digits); + return $this->output; } } diff --git a/src/Algorithms/s0018_4sum/Solution.php b/src/Algorithms/s0018_4sum/Solution.php index 791a357..eee4189 100644 --- a/src/Algorithms/s0018_4sum/Solution.php +++ b/src/Algorithms/s0018_4sum/Solution.php @@ -1,3 +1,5 @@ +$target){ + } else if ($nums[$i] + $nums[$j] + $nums[$k] + $nums[$l] > $target) { $l--; - } - else + } else $k++; } } } - - + + return $result; } } diff --git a/src/Algorithms/s0019_remove_nth_node_from_end_of_list/Solution.php b/src/Algorithms/s0019_remove_nth_node_from_end_of_list/Solution.php index 688eb18..aa20461 100644 --- a/src/Algorithms/s0019_remove_nth_node_from_end_of_list/Solution.php +++ b/src/Algorithms/s0019_remove_nth_node_from_end_of_list/Solution.php @@ -1,3 +1,5 @@ +next != null){ + + while ($a->next != null) { $list[] = $a; - $a=$a->next; + $a = $a->next; $size++; } $list[] = $a; - + $c = null; - - if($size==1){ + + if ($size == 1) { return $c; } - if($size==$n){ - $head=$head->next; + if ($size == $n) { + $head = $head->next; return $head; } - - $b=$list[$size-$n-1]; - - if($b->next->next == null) - $b->next=null; + + $b = $list[$size - $n - 1]; + + if ($b->next->next == null) + $b->next = null; else - $b->next=$b->next->next; - + $b->next = $b->next->next; + return $head; } } \ No newline at end of file diff --git a/src/Algorithms/s0020_valid_parentheses/Solution.php b/src/Algorithms/s0020_valid_parentheses/Solution.php index 58ef5b5..1f95cf8 100644 --- a/src/Algorithms/s0020_valid_parentheses/Solution.php +++ b/src/Algorithms/s0020_valid_parentheses/Solution.php @@ -1,3 +1,5 @@ +>1); - $open=0; - try{ - for($i=0; $i> 1); + $open = 0; + try { + for ($i = 0; $i < strlen($s); ++$i) { + $c = $s[$i]; + $t = 0; + switch ($c) { case '(': ++$t; case '[': ++$t; case '{': - $toClose[$open++]=$t; + $toClose[$open++] = $t; break; case ')': ++$t; case ']': ++$t; case '}': - if($toClose[--$open]!=$t) + if ($toClose[--$open] != $t) return false; } } - return $open==0; - } catch(OutOfBoundsException $x){ + return $open == 0; + } catch (OutOfBoundsException $x) { return false; - } + } } } diff --git a/src/Algorithms/s0021_merge_two_sorted_lists/Solution.php b/src/Algorithms/s0021_merge_two_sorted_lists/Solution.php index a5f7def..c75d367 100644 --- a/src/Algorithms/s0021_merge_two_sorted_lists/Solution.php +++ b/src/Algorithms/s0021_merge_two_sorted_lists/Solution.php @@ -1,3 +1,5 @@ +next; } - + return $res->next; } } diff --git a/src/Algorithms/s0022_generate_parentheses/Solution.php b/src/Algorithms/s0022_generate_parentheses/Solution.php index 04cb18a..e3f1d5e 100644 --- a/src/Algorithms/s0022_generate_parentheses/Solution.php +++ b/src/Algorithms/s0022_generate_parentheses/Solution.php @@ -1,3 +1,5 @@ +list; + return $this->list; } } diff --git a/src/Algorithms/s0023_merge_k_sorted_lists/Solution.php b/src/Algorithms/s0023_merge_k_sorted_lists/Solution.php index e9c0dd7..b3010e7 100644 --- a/src/Algorithms/s0023_merge_k_sorted_lists/Solution.php +++ b/src/Algorithms/s0023_merge_k_sorted_lists/Solution.php @@ -1,3 +1,5 @@ +next = $l1->val <= $l2->val ? $l1 : $l2; $cur = $cur->next; - if($cur->val == $l1->val) { + if ($cur->val == $l1->val) { $l1 = $l1->next; } else { $l2 = $l2->next; diff --git a/src/Algorithms/s0024_swap_nodes_in_pairs/Solution.php b/src/Algorithms/s0024_swap_nodes_in_pairs/Solution.php index 96672b7..14c5ec8 100644 --- a/src/Algorithms/s0024_swap_nodes_in_pairs/Solution.php +++ b/src/Algorithms/s0024_swap_nodes_in_pairs/Solution.php @@ -1,3 +1,5 @@ +next != null){ - + while ($cur != null && $cur->next != null) { + $temp = $cur->val; $cur->val = $cur->next->val; $cur->next->val = $temp; diff --git a/src/Algorithms/s0025_reverse_nodes_in_k_group/Solution.php b/src/Algorithms/s0025_reverse_nodes_in_k_group/Solution.php index 78a08d3..e0241da 100644 --- a/src/Algorithms/s0025_reverse_nodes_in_k_group/Solution.php +++ b/src/Algorithms/s0025_reverse_nodes_in_k_group/Solution.php @@ -1,3 +1,5 @@ +next; $curr->next = $prev; $prev = $curr; $curr = $temp; $count++; } - - if($count<$k){ - while($count!=0){ + + if ($count < $k) { + while ($count != 0) { $temp = $prev->next; $prev->next = $curr; $curr = $prev; @@ -41,9 +43,9 @@ function reverseKGroup($head, $k) { } return $curr; } - - $head->next = self::reverseKGroup($curr,$k); - + + $head->next = self::reverseKGroup($curr, $k); + return $prev; } } diff --git a/src/Algorithms/s0026_remove_duplicates_from_sorted_array/Solution.php b/src/Algorithms/s0026_remove_duplicates_from_sorted_array/Solution.php index 33d8698..a311a28 100644 --- a/src/Algorithms/s0026_remove_duplicates_from_sorted_array/Solution.php +++ b/src/Algorithms/s0026_remove_duplicates_from_sorted_array/Solution.php @@ -1,3 +1,5 @@ + 0) return $dividend; else return -$dividend; } - $l1 = abs($dividend); $l2 = abs($divisor); + $l1 = abs($dividend); + $l2 = abs($divisor); $sol = 0; - while($l1 >= $l2){ - $x = $l2; $y = 1; - while($l1 >= $x){ - $l1-=$x; - $sol+=$y; - $y+=$y; - $x+=$x; + while ($l1 >= $l2) { + $x = $l2; + $y = 1; + while ($l1 >= $x) { + $l1 -= $x; + $sol += $y; + $y += $y; + $x += $x; } } - if ($dividend > 0 && $divisor < 0 || $dividend<0 && $divisor>0) $sol = -$sol; + if ($dividend > 0 && $divisor < 0 || $dividend < 0 && $divisor > 0) $sol = -$sol; return $sol; } } diff --git a/src/Algorithms/s0030_substring_with_concatenation_of_all_words/Solution.php b/src/Algorithms/s0030_substring_with_concatenation_of_all_words/Solution.php index 7f07b9f..5b5d9e0 100644 --- a/src/Algorithms/s0030_substring_with_concatenation_of_all_words/Solution.php +++ b/src/Algorithms/s0030_substring_with_concatenation_of_all_words/Solution.php @@ -1,3 +1,5 @@ += 0; $k--){ - $str = substr($s, $k*$wordLen+$j, $wordLen); + for ($i = 0; $i < $wordLen; $i++) { + for ($j = $i; $j <= $maxIdx; $j += $wordLen) { + for ($k = $listLen - 1; $k >= 0; $k--) { + $str = substr($s, $k * $wordLen + $j, $wordLen); $num = ($temp[$str] == null ? 0 : $temp[$str]) + 1; - if ($num > ($map[$str] == null ? 0 : $map[$str])){ - $j+=$k*$wordLen; + if ($num > ($map[$str] == null ? 0 : $map[$str])) { + $j += $k * $wordLen; break; - }else if ($k == 0) {$sol[] = $j;} - else {$temp[$str] = $num;} + } else if ($k == 0) { + $sol[] = $j; + } else { + $temp[$str] = $num; + } } $temp = []; } diff --git a/src/Algorithms/s0031_next_permutation/Solution.php b/src/Algorithms/s0031_next_permutation/Solution.php index 2fbe9e4..4ac1402 100644 --- a/src/Algorithms/s0031_next_permutation/Solution.php +++ b/src/Algorithms/s0031_next_permutation/Solution.php @@ -1,3 +1,5 @@ += 0; $i--){ - if($nums[$i] < $nums[$i + 1]){ + if (count($nums) == 0) return; + for ($i = count($nums) - 2; $i >= 0; $i--) { + if ($nums[$i] < $nums[$i + 1]) { $j = $i + 1; - while($j < count($nums) && $nums[$j] > $nums[$i]) $j++; + while ($j < count($nums) && $nums[$j] > $nums[$i]) $j++; self::swap($nums, $i, $j - 1); self::reverse($nums, $i + 1, count($nums) - 1); return; @@ -17,10 +19,12 @@ function nextPermutation(&$nums) { } self::reverse($nums, 0, count($nums) - 1); } - function reverse(&$nums, $i, $j){ - while($i < $j) self::swap($nums, $i++, $j--); + + function reverse(&$nums, $i, $j) { + while ($i < $j) self::swap($nums, $i++, $j--); } - function swap(&$nums, $a, $b){ + + function swap(&$nums, $a, $b) { $temp = $nums[$a]; $nums[$a] = $nums[$b]; $nums[$b] = $temp; diff --git a/src/Algorithms/s0032_longest_valid_parentheses/Solution.php b/src/Algorithms/s0032_longest_valid_parentheses/Solution.php index ec51417..cc886c5 100644 --- a/src/Algorithms/s0032_longest_valid_parentheses/Solution.php +++ b/src/Algorithms/s0032_longest_valid_parentheses/Solution.php @@ -1,3 +1,5 @@ + 0 && $i - 2 - $dp[$i - 1] >= 0 && - ($map[$s[$i - 2 - $dp[$i - 1]]] == null ? '?' : $map[$s[$i - 2 - $dp[$i - 1]]]) == $c) - $dp[$i] = $dp[$i - 1] + $dp[$i - 2 - $dp[$i - 1]] + 2; - else if($i > 1 && ($map[$s[$i - 2]] == null ? '?' : $map[$s[$i - 2]]) == $c) { + if ($c != '(' && $c != '[' && $c != '{') { + if ($dp[$i - 1] > 0 && $i - 2 - $dp[$i - 1] >= 0 && + ($map[$s[$i - 2 - $dp[$i - 1]]] == null ? '?' : $map[$s[$i - 2 - $dp[$i - 1]]]) == $c) + $dp[$i] = $dp[$i - 1] + $dp[$i - 2 - $dp[$i - 1]] + 2; + else if ($i > 1 && ($map[$s[$i - 2]] == null ? '?' : $map[$s[$i - 2]]) == $c) { $dp[$i] = $dp[$i - 2] + 2; } } diff --git a/src/Algorithms/s0033_search_in_rotated_sorted_array/Solution.php b/src/Algorithms/s0033_search_in_rotated_sorted_array/Solution.php index b89936c..373cfb9 100644 --- a/src/Algorithms/s0033_search_in_rotated_sorted_array/Solution.php +++ b/src/Algorithms/s0033_search_in_rotated_sorted_array/Solution.php @@ -1,3 +1,5 @@ += $n || $nums[$beg] != $target) ? -1 : $beg; - + $beg = 0; - $end = $n-1; + $end = $n - 1; while ($beg <= $end) { - $mid = $beg + intval(($end-$beg)/2); + $mid = $beg + intval(($end - $beg) / 2); if ($nums[$mid] <= $target) { $beg = $mid + 1; } else { diff --git a/src/Algorithms/s0035_search_insert_position/Solution.php b/src/Algorithms/s0035_search_insert_position/Solution.php index cfbef88..8bbdcdd 100644 --- a/src/Algorithms/s0035_search_insert_position/Solution.php +++ b/src/Algorithms/s0035_search_insert_position/Solution.php @@ -1,3 +1,5 @@ +row = array_fill(0, 9, array_fill(0, 9, false)); @@ -23,14 +25,16 @@ function solveSudoku(&$board) { self::place(0, $board); return; } + function place($n, &$board) { if ($n == 81) { // board = g; $this->found = true; return; } - - $i = intval($n / 9); $j = $n % 9; + + $i = intval($n / 9); + $j = $n % 9; $index = intval(($i / 3)) * 3 + intval(($j / 3)) % 3; if ($board[$i][$j] == '.') { for ($c = 0; $c < 9; ++$c) { @@ -39,21 +43,20 @@ function place($n, &$board) { $this->col[$j][$c] = true; $this->grid[$index][$c] = true; $board[$i][$j] = chr($c + ord('1')); - + self::place($n + 1, $board); - + if ($this->found) return; - + $board[$i][$j] = '.'; $this->row[$i][$c] = false; $this->col[$j][$c] = false; $this->grid[$index][$c] = false; - + } } - } - else + } else self::place($n + 1, $board); return; } diff --git a/src/Algorithms/s0038_count_and_say/Solution.php b/src/Algorithms/s0038_count_and_say/Solution.php index 9a3209f..5a7e0c1 100644 --- a/src/Algorithms/s0038_count_and_say/Solution.php +++ b/src/Algorithms/s0038_count_and_say/Solution.php @@ -1,3 +1,5 @@ +1){ + while ($n > 1) { $sub = ""; - $i=0; $num=0; - $ch = ''; $pre=' '; - while($i<=strlen($s)){ - $ch = ($i==strlen($s) ? ' ': $s[$i]); - if(($pre!=' '&&$ch!=$pre)|| $ch==' '){ - $sub .= ($num==0? 1:$num)."".$pre; + $i = 0; + $num = 0; + $ch = ''; + $pre = ' '; + while ($i <= strlen($s)) { + $ch = ($i == strlen($s) ? ' ' : $s[$i]); + if (($pre != ' ' && $ch != $pre) || $ch == ' ') { + $sub .= ($num == 0 ? 1 : $num) . "" . $pre; $pre = $ch; $num = 1; - }else{ + } else { $num++; - $pre=$ch; + $pre = $ch; } $i++; } $s = $sub; $n--; } - return $s; + return $s; } } diff --git a/src/Algorithms/s0039_combination_sum/Solution.php b/src/Algorithms/s0039_combination_sum/Solution.php index 6d89521..df0e140 100644 --- a/src/Algorithms/s0039_combination_sum/Solution.php +++ b/src/Algorithms/s0039_combination_sum/Solution.php @@ -1,3 +1,5 @@ +sol; } - - function search($target, $list, $start){ + + function search($target, $list, $start) { if ($target == 0) { - array_push($this->sol, $list); - return; - } - for ($i = $start; $i < count($this->nums); $i++){ + array_push($this->sol, $list); + return; + } + for ($i = $start; $i < count($this->nums); $i++) { if ($this->nums[$i] > $target) break; else { array_push($list, $this->nums[$i]); diff --git a/src/Algorithms/s0040_combination_sum_ii/Solution.php b/src/Algorithms/s0040_combination_sum_ii/Solution.php index e9790ff..9776728 100644 --- a/src/Algorithms/s0040_combination_sum_ii/Solution.php +++ b/src/Algorithms/s0040_combination_sum_ii/Solution.php @@ -1,3 +1,5 @@ + $cur && $cand[$i] == $cand[$i-1]) continue; + for ($i = $cur; $i < count($cand); $i++) { + if ($i > $cur && $cand[$i] == $cand[$i - 1]) continue; array_push($path, $cand[$i]); - self::dfs_com($cand, $i+1, $target - $cand[$i], $path, $res); + self::dfs_com($cand, $i + 1, $target - $cand[$i], $path, $res); array_pop($path); } } diff --git a/src/Algorithms/s0041_first_missing_positive/Solution.php b/src/Algorithms/s0041_first_missing_positive/Solution.php index 27a8a13..3b0b7e6 100644 --- a/src/Algorithms/s0041_first_missing_positive/Solution.php +++ b/src/Algorithms/s0041_first_missing_positive/Solution.php @@ -1,3 +1,5 @@ += 1 && $nums[$i] <= count($nums) && $nums[$nums[$i] - 1] != $nums[$i]) { + if (count($nums) == 0) return 1; + for ($i = 0; $i < count($nums); $i++) { + while (($nums[$i] != $i + 1) && $nums[$i] >= 1 && $nums[$i] <= count($nums) && $nums[$nums[$i] - 1] != $nums[$i]) { $tmp = $nums[$i] - 1; $nums[$i] = $nums[$tmp]; - $nums[$tmp] = $tmp + 1; + $nums[$tmp] = $tmp + 1; } } - for($i = 0;$i < count($nums);$i++) { - if($nums[$i] != $i + 1) return $i + 1; + for ($i = 0; $i < count($nums); $i++) { + if ($nums[$i] != $i + 1) return $i + 1; } return count($nums) + 1; } diff --git a/src/Algorithms/s0042_trapping_rain_water/Solution.php b/src/Algorithms/s0042_trapping_rain_water/Solution.php index e644fa9..8f25a98 100644 --- a/src/Algorithms/s0042_trapping_rain_water/Solution.php +++ b/src/Algorithms/s0042_trapping_rain_water/Solution.php @@ -1,3 +1,5 @@ += 0; $i--){ + for ($i = count($height) - 1; $i >= 0; $i--) { $max = max($max, $height[$i]); $memo[$i] = min($memo[$i], $max); } - + $volume = 0; - for($i = 0; $i < count($height); $i++){ + for ($i = 0; $i < count($height); $i++) { $volume += $memo[$i] - $height[$i]; } - + return $volume; } } diff --git a/src/Algorithms/s0043_multiply_strings/Solution.php b/src/Algorithms/s0043_multiply_strings/Solution.php index 31eff98..e1e9c3b 100644 --- a/src/Algorithms/s0043_multiply_strings/Solution.php +++ b/src/Algorithms/s0043_multiply_strings/Solution.php @@ -1,3 +1,5 @@ += 0; $j--) { $prod = (ord($num1[$j]) - ord('0')) * (ord($num2[$i]) - ord('0')); - $prod += $res[$a+$b]; - $carry = intval($prod/10); - $digit = $prod%10; - $res[$a+$b] = $digit; - $res[$a+$b+1] += $carry; + $prod += $res[$a + $b]; + $carry = intval($prod / 10); + $digit = $prod % 10; + $res[$a + $b] = $digit; + $res[$a + $b + 1] += $carry; $b++; } $a++; } $sb = ""; for ($i = count($res) - 1; $i >= 0; $i--) { - if ($i == count($res) -1 && $res[count($res) - 1] == 0) continue; + if ($i == count($res) - 1 && $res[count($res) - 1] == 0) continue; $sb .= chr($res[$i] + ord('0')); } return $sb; diff --git a/src/Algorithms/s0044_wildcard_matching/Solution.php b/src/Algorithms/s0044_wildcard_matching/Solution.php index 2c9d562..5e9b637 100644 --- a/src/Algorithms/s0044_wildcard_matching/Solution.php +++ b/src/Algorithms/s0044_wildcard_matching/Solution.php @@ -1,3 +1,5 @@ +tot++; - else{ - for($i = 0; $i < $n; $i++){ + + function totalQueens($n, $cur, &$col) { + if ($cur == $n) $this->tot++; + else { + for ($i = 0; $i < $n; $i++) { $ok = true; $col[$cur] = $i; - for($j = 0; $j < $cur; $j++){ - if($col[$cur] == $col[$j] || $cur+$col[$cur] == $j + $col[$j] || $cur-$col[$cur] == $j - $col[$j]){ + for ($j = 0; $j < $cur; $j++) { + if ($col[$cur] == $col[$j] || $cur + $col[$cur] == $j + $col[$j] || $cur - $col[$cur] == $j - $col[$j]) { $ok = false; break; } } - if($ok){ - self::totalQueens($n,$cur+1,$col); + if ($ok) { + self::totalQueens($n, $cur + 1, $col); } } } diff --git a/src/Algorithms/s0053_maximum_subarray/Solution.php b/src/Algorithms/s0053_maximum_subarray/Solution.php index 3689c52..090e419 100644 --- a/src/Algorithms/s0053_maximum_subarray/Solution.php +++ b/src/Algorithms/s0053_maximum_subarray/Solution.php @@ -1,3 +1,5 @@ +$nums[$i]+$sum?$nums[$i]:$nums[$i]+$sum; - $max = $max > $sum? $max : $sum; + $max = $sum; + for ($i = 1; $i < $n; $i++) { + $sum = $nums[$i] > $nums[$i] + $sum ? $nums[$i] : $nums[$i] + $sum; + $max = $max > $sum ? $max : $sum; } return $max; } diff --git a/src/Algorithms/s0054_spiral_matrix/Solution.php b/src/Algorithms/s0054_spiral_matrix/Solution.php index e8c5187..283b03a 100644 --- a/src/Algorithms/s0054_spiral_matrix/Solution.php +++ b/src/Algorithms/s0054_spiral_matrix/Solution.php @@ -1,3 +1,5 @@ + 1) - { - while ($j < $col - 1) - { - $j++; - array_push($res, $matrix[$i][$j]); - $count--; - } - while ($i < $row - 1) - { - $i++; - array_push($res, $matrix[$i][$j]); - $count--; - } - $row--; - $col--; - if ($count == 1) - break; - while ($j > $start1) - { - $j--; - array_push($res, $matrix[$i][$j]); - $count--; - } - while ($i > $start2) - { - $i--; - array_push($res, $matrix[$i][$j]); - $count--; - } - $start1++; - $start2++; - } - return $res; + if (count($matrix) == 0) + return []; + $count = count($matrix) * count($matrix[0]); + $res = []; + $i = 0; + $j = 0; + $row = count($matrix); + $col = count($matrix[0]); + $start1 = 0; + $start2 = 1; + array_push($res, $matrix[0][0]); + while ($count > 1) { + while ($j < $col - 1) { + $j++; + array_push($res, $matrix[$i][$j]); + $count--; + } + while ($i < $row - 1) { + $i++; + array_push($res, $matrix[$i][$j]); + $count--; + } + $row--; + $col--; + if ($count == 1) + break; + while ($j > $start1) { + $j--; + array_push($res, $matrix[$i][$j]); + $count--; + } + while ($i > $start2) { + $i--; + array_push($res, $matrix[$i][$j]); + $count--; + } + $start1++; + $start2++; + } + return $res; } } diff --git a/src/Algorithms/s0055_jump_game/Solution.php b/src/Algorithms/s0055_jump_game/Solution.php index 238f1c3..d4b713e 100644 --- a/src/Algorithms/s0055_jump_game/Solution.php +++ b/src/Algorithms/s0055_jump_game/Solution.php @@ -1,3 +1,5 @@ +start; $end = $interval->end; - + while (++$i < count($intervals) && $intervals[$i]->start <= $end) { if ($end < $intervals[$i]->end) { $end = $intervals[$i]->end; @@ -38,7 +40,7 @@ function merge($intervals) { } array_push($mergedIntervals, new Interval($start, $end)); } - + return $mergedIntervals; } } diff --git a/src/Algorithms/s0057_insert_interval/Solution.php b/src/Algorithms/s0057_insert_interval/Solution.php index bb0cad1..2fc86ad 100644 --- a/src/Algorithms/s0057_insert_interval/Solution.php +++ b/src/Algorithms/s0057_insert_interval/Solution.php @@ -1,3 +1,5 @@ +start; $e = $newInterval->end; - - foreach($intervals as $i) { - if($i->start > $e) { - array_push($res, new Interval($s,$e)); + + foreach ($intervals as $i) { + if ($i->start > $e) { + array_push($res, new Interval($s, $e)); $s = $i->start; $e = $i->end; } - - if($s <= $i->end) { + + if ($s <= $i->end) { $s = min($s, $i->start); $e = max($e, $i->end); - } - else { + } else { array_push($res, $i); } } - - array_push($res, new Interval($s,$e)); - return $res; + + array_push($res, new Interval($s, $e)); + return $res; } } diff --git a/src/Algorithms/s0058_length_of_last_word/Solution.php b/src/Algorithms/s0058_length_of_last_word/Solution.php index 5a810cc..d449764 100644 --- a/src/Algorithms/s0058_length_of_last_word/Solution.php +++ b/src/Algorithms/s0058_length_of_last_word/Solution.php @@ -1,3 +1,5 @@ +=$k;$j--)$res[$i][$j]=$next++; - for(++$j,--$i;$i>$k;$i--)$res[$i][$j]=$next++; + $res = array_fill(0, $n, array_fill(0, $n, 0)); + $next = 1; + for ($k = 0; $k < intval($n / 2) + $n % 2; $k++) { + $i = $k; + for ($j = $i; $j < $n - $k; $j++) $res[$i][$j] = $next++; + for (--$j, ++$i; $i < $n - $k; $i++) $res[$i][$j] = $next++; + for (--$j, --$i; $j >= $k; $j--) $res[$i][$j] = $next++; + for (++$j, --$i; $i > $k; $i--) $res[$i][$j] = $next++; } return $res; } diff --git a/src/Algorithms/s0060_permutation_sequence/Solution.php b/src/Algorithms/s0060_permutation_sequence/Solution.php index d489c9b..3342d46 100644 --- a/src/Algorithms/s0060_permutation_sequence/Solution.php +++ b/src/Algorithms/s0060_permutation_sequence/Solution.php @@ -1,3 +1,5 @@ +next = $head1; $cur = $dummyHead->next; $pre = $dummyHead; - while($k > 0){ + while ($k > 0) { $pre = $cur; $cur = $cur->next; $k--; @@ -35,18 +37,20 @@ function rotateRight($head, $k) { $head2 = self::reverse(null, $cur); return self::reverse($head2, $head1); } - function getLen($head){ + + function getLen($head) { $cnt = 0; - while($head != null){ + while ($head != null) { $cnt++; $head = $head->next; } return $cnt; } - function reverse($pre,$head) { + + function reverse($pre, $head) { $tmp; $cur = $head; - while($cur != null) { + while ($cur != null) { $tmp = $cur->next; $cur->next = $pre; $pre = $cur; diff --git a/src/Algorithms/s0062_unique_paths/Solution.php b/src/Algorithms/s0062_unique_paths/Solution.php index 7c94e9f..0d9edfd 100644 --- a/src/Algorithms/s0062_unique_paths/Solution.php +++ b/src/Algorithms/s0062_unique_paths/Solution.php @@ -1,3 +1,5 @@ +=48 && ord($s[0])<=57)){ + if (strlen($s) == 1 && !(ord($s[0]) >= 48 && ord($s[0]) <= 57)) { return false; } - $s=trim($s); - for($i=0;$i=48 && $t<=57) || $t==101 || $t== 43 || $t==45 || $t==46)){ + if (!(($t >= 48 && $t <= 57) || $t == 101 || $t == 43 || $t == 45 || $t == 46)) { return false; } - if($t == 101){ - if($isE){ + if ($t == 101) { + if ($isE) { return false; } - if($i == strlen($s)-1){ + if ($i == strlen($s) - 1) { return false; } - if($lastChar==43 || $lastChar==45 || $lastChar==46){ - if($llastChar == -1){ + if ($lastChar == 43 || $lastChar == 45 || $lastChar == 46) { + if ($llastChar == -1) { return false; } } $isE = true; } - if($t == 46 ){ - if($isE){ + if ($t == 46) { + if ($isE) { return false; } - if($i == strlen($s)-1 && !($lastChar>=48 && $lastChar<=57)){ + if ($i == strlen($s) - 1 && !($lastChar >= 48 && $lastChar <= 57)) { return false; } - if($isPoint){ + if ($isPoint) { return false; } - $isPoint = true; + $isPoint = true; } - if(($t==43 || $t==45)&& $i!=0 && ($lastChar!=101 ||($lastChar==101 && $i == strlen($s)-1))){ - return false; + if (($t == 43 || $t == 45) && $i != 0 && ($lastChar != 101 || ($lastChar == 101 && $i == strlen($s) - 1))) { + return false; } $llastChar = $lastChar; $lastChar = $t; diff --git a/src/Algorithms/s0066_plus_one/Solution.php b/src/Algorithms/s0066_plus_one/Solution.php index 9e51d6c..ffa07ec 100644 --- a/src/Algorithms/s0066_plus_one/Solution.php +++ b/src/Algorithms/s0066_plus_one/Solution.php @@ -1,3 +1,5 @@ +=0;$i--){ - $temp=($digits[$i]+$carry)%10; - $carry=intval(($digits[$i]+$carry)/10); - $digits[$i]=$temp; + $carry = 1; + for ($i = count($digits) - 1; $i >= 0; $i--) { + $temp = ($digits[$i] + $carry) % 10; + $carry = intval(($digits[$i] + $carry) / 10); + $digits[$i] = $temp; } - if($carry==0)return $digits; - else{ - $res=array_fill(0, count($digits) + 1, 0); - $res[0]=$carry; - for($i=0;$i= 0 || $j >= 0 || $carry > 0) - { + + while ($i >= 0 || $j >= 0 || $carry > 0) { $sum = $carry; - if($i >= 0) $sum += ord($a[$i--]) - ord('0'); - if($j >= 0) $sum += ord($b[$j--]) - ord('0'); + if ($i >= 0) $sum += ord($a[$i--]) - ord('0'); + if ($j >= 0) $sum += ord($b[$j--]) - ord('0'); $sb .= chr($sum % 2 + ord('0')); $carry = intval($sum / 2); } diff --git a/src/Algorithms/s0068_text_justification/Solution.php b/src/Algorithms/s0068_text_justification/Solution.php index 0941b9e..9f03d12 100644 --- a/src/Algorithms/s0068_text_justification/Solution.php +++ b/src/Algorithms/s0068_text_justification/Solution.php @@ -1,3 +1,5 @@ + 0) $sb .= ' '; diff --git a/src/Algorithms/s0069_sqrtx/Solution.php b/src/Algorithms/s0069_sqrtx/Solution.php index 6a51464..d990bb9 100644 --- a/src/Algorithms/s0069_sqrtx/Solution.php +++ b/src/Algorithms/s0069_sqrtx/Solution.php @@ -1,3 +1,5 @@ +isEmpty()) $stack->pop();} - else if($cur != "" && $cur != ".") $stack->push($cur); + foreach (explode("/", $path) as $cur) { + if ($cur == "..") { + if (!$stack->isEmpty()) $stack->pop(); + } else if ($cur != "" && $cur != ".") $stack->push($cur); } - - if($stack->isEmpty()) return "/"; + + if ($stack->isEmpty()) return "/"; $sb = ""; - while(!$stack->isEmpty()) $sb .= "/" . $stack->shift(); + while (!$stack->isEmpty()) $sb .= "/" . $stack->shift(); return $sb; } } diff --git a/src/Algorithms/s0072_edit_distance/Solution.php b/src/Algorithms/s0072_edit_distance/Solution.php index c1acd94..fd7dc91 100644 --- a/src/Algorithms/s0072_edit_distance/Solution.php +++ b/src/Algorithms/s0072_edit_distance/Solution.php @@ -1,3 +1,5 @@ + $n1) return self::minDistance($word2, $word1); - $dp = array_fill(0, $n2+1, 0); + $dp = array_fill(0, $n2 + 1, 0); for ($j = 0; $j <= $n2; $j++) $dp[$j] = $j; for ($i = 1; $i <= $n1; $i++) { @@ -17,8 +20,8 @@ function minDistance($word1, $word2) { $dp[0] = $i; for ($j = 1; $j <= $n2; $j++) { $tmp = $dp[$j]; - $dp[$j] = $word1[$i-1] != $word2[$j-1] - ? 1 + min($pre, min($dp[$j], $dp[$j-1])) + $dp[$j] = $word1[$i - 1] != $word2[$j - 1] + ? 1 + min($pre, min($dp[$j], $dp[$j - 1])) : $pre; $pre = $tmp; } diff --git a/src/Algorithms/s0073_set_matrix_zeroes/Solution.php b/src/Algorithms/s0073_set_matrix_zeroes/Solution.php index 2716852..dbedc6e 100644 --- a/src/Algorithms/s0073_set_matrix_zeroes/Solution.php +++ b/src/Algorithms/s0073_set_matrix_zeroes/Solution.php @@ -1,3 +1,5 @@ += 0) { if ($matrix[$row][$col] == $target) return true; if ($matrix[$row][$col] < $target) $row++; diff --git a/src/Algorithms/s0075_sort_colors/Solution.php b/src/Algorithms/s0075_sort_colors/Solution.php index e16107f..7c9aacb 100644 --- a/src/Algorithms/s0075_sort_colors/Solution.php +++ b/src/Algorithms/s0075_sort_colors/Solution.php @@ -1,3 +1,5 @@ + 0){ + + while ($right < $N) { + while ($right < $N && $T > 0) { if (--$tCount[ord($s[$right++])] >= 0) $T--; } //At this point we are either at the end or we have a substring in S that covers all of T. - while ($left < $right && $T == 0){ - if ($right-$left < $min){ + while ($left < $right && $T == 0) { + if ($right - $left < $min) { $min = $right - $left; $res = [$left, $right]; } if (++$tCount[ord($s[$left++])] > 0) $T++; } } - + return $min == 2147483647 ? "" : substr($s, $res[0], $res[1] - $res[0]); } } diff --git a/src/Algorithms/s0077_combinations/Solution.php b/src/Algorithms/s0077_combinations/Solution.php index 979a73d..b06064f 100644 --- a/src/Algorithms/s0077_combinations/Solution.php +++ b/src/Algorithms/s0077_combinations/Solution.php @@ -1,3 +1,5 @@ + $m*$n) return false; + $n = count($board); + $m = count($board[0]); + if (strlen($word) > $m * $n) return false; $visited = array_fill(0, $n, array_fill(0, $m, false)); - for ($i = 0; $i < $n; $i++) for ($j = 0; $j < $m; $j++) + for ($i = 0; $i < $n; $i++) for ($j = 0; $j < $m; $j++) if (self::help($i, $j, 0, $board, $word, $visited)) return true; return false; } - - function help($i, $j, $k, $board, $word, $visited){ + + function help($i, $j, $k, $board, $word, $visited) { if ($k == strlen($word)) return true; if ($i >= count($board) || $i < 0 || $j >= count($board[0]) || $j < 0) return false; if ($visited[$i][$j] || $board[$i][$j] != $word[$k]) return false; $visited[$i][$j] = true; - $b = self::help($i+1, $j, $k+1, $board, $word, $visited) || - self::help($i-1, $j, $k+1, $board, $word, $visited) || - self::help($i, $j-1, $k+1, $board, $word, $visited) || - self::help($i, $j+1, $k+1, $board, $word, $visited); + $b = self::help($i + 1, $j, $k + 1, $board, $word, $visited) || + self::help($i - 1, $j, $k + 1, $board, $word, $visited) || + self::help($i, $j - 1, $k + 1, $board, $word, $visited) || + self::help($i, $j + 1, $k + 1, $board, $word, $visited); $visited[$i][$j] = false; return $b; } diff --git a/src/Algorithms/s0080_remove_duplicates_from_sorted_array_ii/Solution.php b/src/Algorithms/s0080_remove_duplicates_from_sorted_array_ii/Solution.php index f4badd5..0a1ae0d 100644 --- a/src/Algorithms/s0080_remove_duplicates_from_sorted_array_ii/Solution.php +++ b/src/Algorithms/s0080_remove_duplicates_from_sorted_array_ii/Solution.php @@ -1,3 +1,5 @@ +next == null) return $head; + if ($head == null || $head->next == null) return $head; $dummy = new ListNode(-1); $dummy->next = $head; - $prev=$dummy; - $slow=$dummy->next; - $fast=$slow->next; - while($slow != null && $fast != null) { - if($slow->val == $fast->val) { - while($fast != null && $slow->val == $fast->val) { + $prev = $dummy; + $slow = $dummy->next; + $fast = $slow->next; + while ($slow != null && $fast != null) { + if ($slow->val == $fast->val) { + while ($fast != null && $slow->val == $fast->val) { $fast = $fast->next; } $prev->next = $fast; diff --git a/src/Algorithms/s0083_remove_duplicates_from_sorted_list/Solution.php b/src/Algorithms/s0083_remove_duplicates_from_sorted_list/Solution.php index ebdf938..6b494cc 100644 --- a/src/Algorithms/s0083_remove_duplicates_from_sorted_list/Solution.php +++ b/src/Algorithms/s0083_remove_duplicates_from_sorted_list/Solution.php @@ -1,3 +1,5 @@ +next == null) return $head; + if ($head == null || $head->next == null) return $head; $prev = $head; $node = $head->next; - while( $node!= null){ - if($node->val != $prev->val){ + while ($node != null) { + if ($node->val != $prev->val) { $prev = $node; $node = $node->next; - }else{ + } else { $prev->next = $node->next; $node = $node->next; } diff --git a/src/Algorithms/s0084_largest_rectangle_in_histogram/Solution.php b/src/Algorithms/s0084_largest_rectangle_in_histogram/Solution.php index b2d206a..f66725e 100644 --- a/src/Algorithms/s0084_largest_rectangle_in_histogram/Solution.php +++ b/src/Algorithms/s0084_largest_rectangle_in_histogram/Solution.php @@ -1,3 +1,5 @@ += $heights[end($stack)])) array_push($stack, $i++); + while ($i < count($heights) || count($stack) != 0) + if ($i < count($heights) && (count($stack) == 0 || $heights[$i] >= $heights[end($stack)])) array_push($stack, $i++); else $max = max($max, $heights[array_pop($stack)] * (count($stack) == 0 ? $i : $i - end($stack) - 1)); return $max; } diff --git a/src/Algorithms/s0085_maximal_rectangle/Solution.php b/src/Algorithms/s0085_maximal_rectangle/Solution.php index d92b403..fc2c2bb 100644 --- a/src/Algorithms/s0085_maximal_rectangle/Solution.php +++ b/src/Algorithms/s0085_maximal_rectangle/Solution.php @@ -1,3 +1,5 @@ +next == null) return $head; - //split the answer into two part and then combine them, use prevPart and restPart as dummy heads; + if ($head == null || $head->next == null) return $head; + //split the answer into two part and then combine them, use prevPart and restPart as dummy heads; $prevPart = new ListNode(-1); $restPart = new ListNode(-1); $prev = $prevPart; $rest = $restPart; - while($head != null){ - if($head->val < $x){ + while ($head != null) { + if ($head->val < $x) { $prev->next = new ListNode($head->val); $prev = $prev->next; - }else{ + } else { $rest->next = new ListNode($head->val); $rest = $rest->next; } $head = $head->next; } $tail = self::getTail($prevPart); - //put `>= val` numbers at tail of `< val` numbers + //put `>= val` numbers at tail of `< val` numbers $tail->next = $restPart->next; return $prevPart->next; } - - function getTail($head){ - while($head->next != null){ + + function getTail($head) { + while ($head->next != null) { $head = $head->next; } return $head; diff --git a/src/Algorithms/s0087_scramble_string/Solution.php b/src/Algorithms/s0087_scramble_string/Solution.php index 2ff3134..1501ca2 100644 --- a/src/Algorithms/s0087_scramble_string/Solution.php +++ b/src/Algorithms/s0087_scramble_string/Solution.php @@ -1,3 +1,5 @@ += 0; $c--) { - if ($i>=0 && $j>=0 && $nums1[$i] >= $nums2[$j]) { + $i = $m - 1; + $j = $n - 1; + $x = count($nums1); + for ($c = count($nums1) - 1; $c >= 0; $c--) { + if ($i >= 0 && $j >= 0 && $nums1[$i] >= $nums2[$j]) { $nums1[$c] = $nums1[$i]; --$i; - } else if ($i>=0 && $j>=0 && $nums2[$j] > $nums1[$i]) { + } else if ($i >= 0 && $j >= 0 && $nums2[$j] > $nums1[$i]) { $nums1[$c] = $nums2[$j]; --$j; - } else if($i<0 && $j>=0) { + } else if ($i < 0 && $j >= 0) { $nums1[$c] = $nums2[$j]; --$j; } else { diff --git a/src/Algorithms/s0089_gray_code/Solution.php b/src/Algorithms/s0089_gray_code/Solution.php index 2ec94b9..7d951d7 100644 --- a/src/Algorithms/s0089_gray_code/Solution.php +++ b/src/Algorithms/s0089_gray_code/Solution.php @@ -1,3 +1,5 @@ + $index && $nums[$i-1] == $nums[$i]) { + for ($i = $index; $i < count($nums); $i++) { + if ($i > $index && $nums[$i - 1] == $nums[$i]) { continue; } array_push($list, $nums[$i]); array_push($result, $list); - self::dfs($nums, $list, $result, $i+1); + self::dfs($nums, $list, $result, $i + 1); array_pop($list); } } diff --git a/src/Algorithms/s0091_decode_ways/Solution.php b/src/Algorithms/s0091_decode_ways/Solution.php index a54fd4c..5282aec 100644 --- a/src/Algorithms/s0091_decode_ways/Solution.php +++ b/src/Algorithms/s0091_decode_ways/Solution.php @@ -1,3 +1,5 @@ += 0; $i--) - { - $digit = ord($s[$i]) - ord('0'); - - if($digit == 0) - $result = 0; - else - $result = $first + ($digit * 10 + $prev <= 26 ? $second : 0); - - $second = $first; - $first = $result; - $prev = $digit; - } - return $result; + if (strlen($s) == 0) + return 0; + + $prev = 26; + $result = 0; + $first = 1; + $second = 1; + + for ($i = strlen($s) - 1; $i >= 0; $i--) { + $digit = ord($s[$i]) - ord('0'); + + if ($digit == 0) + $result = 0; + else + $result = $first + ($digit * 10 + $prev <= 26 ? $second : 0); + + $second = $first; + $first = $result; + $prev = $digit; + } + return $result; } } diff --git a/src/Algorithms/s0092_reverse_linked_list_ii/Solution.php b/src/Algorithms/s0092_reverse_linked_list_ii/Solution.php index cf07893..8ffb459 100644 --- a/src/Algorithms/s0092_reverse_linked_list_ii/Solution.php +++ b/src/Algorithms/s0092_reverse_linked_list_ii/Solution.php @@ -1,3 +1,5 @@ +next = $head; - + // this loop aims to find the connection node and the first node to be reversed. - for($i=0; $i<$m-1; $i++) { + for ($i = 0; $i < $m - 1; $i++) { $pre = $pre->next; - } + } $connection = $pre; $tail = $cur = $pre->next; - - $temp; + + $temp; // this loop is just like the similar problem(https://leetcode.com/problems/reverse-linked-list/) - for($i=$m; $i<=$n; $i++) { + for ($i = $m; $i <= $n; $i++) { $temp = $cur->next; $cur->next = $pre; $pre = $cur; $cur = $temp; } - + // adjust the connection points $tail->next = $cur; $connection->next = $pre; - return $dummy->next; + return $dummy->next; } } diff --git a/src/Algorithms/s0093_restore_ip_addresses/Solution.php b/src/Algorithms/s0093_restore_ip_addresses/Solution.php index 6e47e1e..4ec305d 100644 --- a/src/Algorithms/s0093_restore_ip_addresses/Solution.php +++ b/src/Algorithms/s0093_restore_ip_addresses/Solution.php @@ -1,3 +1,5 @@ +s[$nextIdx]) - ord('0'); $possibleNum = $num == -1 ? $nextDigit : $num * 10 + $nextDigit; - if ($possibleNum <= 255 ) { + if ($possibleNum <= 255) { //trying increase this position next (if it's not 0) if ($possibleNum > 0 || ($possibleNum == 0 && $nextIdx == strlen($this->s) - 1)) self::helper($possibleNum, $nextIdx + 1, $partIdx); @@ -40,11 +42,12 @@ function helper($num, $nextIdx, $partIdx) { $this->parts[$partIdx] = -1; } } + function parseIp() { $sb = ""; for ($i = 0; $i < count($this->parts); $i++) { $sb .= $this->parts[$i]; - if ( $i < count($this->parts) - 1) + if ($i < count($this->parts) - 1) $sb .= '.'; } array_push($this->res, $sb); diff --git a/src/Algorithms/s0094_binary_tree_inorder_traversal/Solution.php b/src/Algorithms/s0094_binary_tree_inorder_traversal/Solution.php index fe0df35..9bb656f 100644 --- a/src/Algorithms/s0094_binary_tree_inorder_traversal/Solution.php +++ b/src/Algorithms/s0094_binary_tree_inorder_traversal/Solution.php @@ -1,3 +1,5 @@ +val <= $min->val) || ($max != null && $node->val >= $max->val)) return false; diff --git a/src/Algorithms/s0099_recover_binary_search_tree/Solution.php b/src/Algorithms/s0099_recover_binary_search_tree/Solution.php index 5ae502f..9a5b2f1 100644 --- a/src/Algorithms/s0099_recover_binary_search_tree/Solution.php +++ b/src/Algorithms/s0099_recover_binary_search_tree/Solution.php @@ -1,3 +1,5 @@ +val < $prev->val) { if ($first == null) $first = $prev; $second = $current; - } - $prev = $current; $current = $current->right; + } + $prev = $current; + $current = $current->right; } // swap - $temp = $first->val; $first->val = $second->val; $second->val = $temp; + $temp = $first->val; + $first->val = $second->val; + $second->val = $temp; } } diff --git a/src/Algorithms/s0100_same_tree/Solution.php b/src/Algorithms/s0100_same_tree/Solution.php index f2ac9fb..046e4a1 100644 --- a/src/Algorithms/s0100_same_tree/Solution.php +++ b/src/Algorithms/s0100_same_tree/Solution.php @@ -1,3 +1,5 @@ +val == $q->val) && self::isSameTree($p->left, $q->left) && self::isSameTree($p->right,$q->right); + + return ($p->val == $q->val) && self::isSameTree($p->left, $q->left) && self::isSameTree($p->right, $q->right); } } diff --git a/src/Algorithms/s0101_symmetric_tree/Solution.php b/src/Algorithms/s0101_symmetric_tree/Solution.php index 590e147..cbf4652 100644 --- a/src/Algorithms/s0101_symmetric_tree/Solution.php +++ b/src/Algorithms/s0101_symmetric_tree/Solution.php @@ -1,3 +1,5 @@ +left, $root->right); } - - function helper($left, $right){ + + function helper($left, $right) { //3. Both must be null, or false - if($left==null || $right==null) - return $left==$right; - + if ($left == null || $right == null) + return $left == $right; + //4. Check values and next level of children - return $left->val==$right->val && self::helper($left->left, $right->right) && self::helper($left->right, $right->left); + return $left->val == $right->val && self::helper($left->left, $right->right) && self::helper($left->right, $right->left); } } diff --git a/src/Algorithms/s0102_binary_tree_level_order_traversal/Solution.php b/src/Algorithms/s0102_binary_tree_level_order_traversal/Solution.php index cf24342..5bf6059 100644 --- a/src/Algorithms/s0102_binary_tree_level_order_traversal/Solution.php +++ b/src/Algorithms/s0102_binary_tree_level_order_traversal/Solution.php @@ -1,3 +1,5 @@ +val); - }else{ + } else { array_push($lists[$depth], $root->val); } - self::levelOrderTraverse($root->left,$depth+1,$lists); - self::levelOrderTraverse($root->right,$depth+1,$lists); + self::levelOrderTraverse($root->left, $depth + 1, $lists); + self::levelOrderTraverse($root->right, $depth + 1, $lists); } } diff --git a/src/Algorithms/s0103_binary_tree_zigzag_level_order_traversal/Solution.php b/src/Algorithms/s0103_binary_tree_zigzag_level_order_traversal/Solution.php index 9b227a4..a7fa16e 100644 --- a/src/Algorithms/s0103_binary_tree_zigzag_level_order_traversal/Solution.php +++ b/src/Algorithms/s0103_binary_tree_zigzag_level_order_traversal/Solution.php @@ -1,3 +1,5 @@ + 0){ + while (count($queue) > 0) { $size = count($queue); $list = []; - for ($i = 0; $i < $size; $i++){ + for ($i = 0; $i < $size; $i++) { $node = array_shift($queue); - if ($leftRight){ + if ($leftRight) { array_push($list, $node->val); } else { array_splice($list, 0, 0, $node->val); @@ -34,7 +36,7 @@ function zigzagLevelOrder($root) { array_push($result, $list); $leftRight = !$leftRight; } - - return $result; + + return $result; } } diff --git a/src/Algorithms/s0104_maximum_depth_of_binary_tree/Solution.php b/src/Algorithms/s0104_maximum_depth_of_binary_tree/Solution.php index d469cc1..804eafc 100644 --- a/src/Algorithms/s0104_maximum_depth_of_binary_tree/Solution.php +++ b/src/Algorithms/s0104_maximum_depth_of_binary_tree/Solution.php @@ -1,3 +1,5 @@ +left), self::maxDepth($root->right) ); + if ($root == null) return 0; + return 1 + max(self::maxDepth($root->left), self::maxDepth($root->right)); } } diff --git a/src/Algorithms/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/Solution.php b/src/Algorithms/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/Solution.php index 93852ca..2a27a2f 100644 --- a/src/Algorithms/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/Solution.php +++ b/src/Algorithms/s0105_construct_binary_tree_from_preorder_and_inorder_traversal/Solution.php @@ -1,3 +1,5 @@ += count($preorder) || $start > $end) { return null; diff --git a/src/Algorithms/s0106_construct_binary_tree_from_inorder_and_postorder_traversal/Solution.php b/src/Algorithms/s0106_construct_binary_tree_from_inorder_and_postorder_traversal/Solution.php index c09facc..ede1bd1 100644 --- a/src/Algorithms/s0106_construct_binary_tree_from_inorder_and_postorder_traversal/Solution.php +++ b/src/Algorithms/s0106_construct_binary_tree_from_inorder_and_postorder_traversal/Solution.php @@ -1,3 +1,5 @@ +$inEnd || $postEnd<0) return null; - $root=new TreeNode($postorder[$postEnd]); + if ($inStart > $inEnd || $postEnd < 0) return null; + $root = new TreeNode($postorder[$postEnd]); /** - manually check the index of postorder[postEnd] in inorder arr - **/ - $index=0; - while($inorder[$index]!=$root->val) $index++; - $root->left=self::recursive($inorder, $inStart, $index-1, $postorder, $postEnd-1-($inEnd-$index)); - $root->right=self::recursive($inorder, $index+1, $inEnd, $postorder, $postEnd-1); + * manually check the index of postorder[postEnd] in inorder arr + **/ + $index = 0; + while ($inorder[$index] != $root->val) $index++; + $root->left = self::recursive($inorder, $inStart, $index - 1, $postorder, $postEnd - 1 - ($inEnd - $index)); + $root->right = self::recursive($inorder, $index + 1, $inEnd, $postorder, $postEnd - 1); return $root; } } diff --git a/src/Algorithms/s0107_binary_tree_level_order_traversal_ii/Solution.php b/src/Algorithms/s0107_binary_tree_level_order_traversal_ii/Solution.php index 3d500b7..7ba0b54 100644 --- a/src/Algorithms/s0107_binary_tree_level_order_traversal_ii/Solution.php +++ b/src/Algorithms/s0107_binary_tree_level_order_traversal_ii/Solution.php @@ -1,3 +1,5 @@ +val); - + $left = self::levelOrderBottom($root->left); $right = self::levelOrderBottom($root->right); - + // Return directly on leaf will cause the depth of left/right tree are not the same // need to merge the lists based on different index. $startIdx = abs(count($left) - count($right)); diff --git a/src/Algorithms/s0108_convert_sorted_array_to_binary_search_tree/Solution.php b/src/Algorithms/s0108_convert_sorted_array_to_binary_search_tree/Solution.php index 8f46af3..6516b08 100644 --- a/src/Algorithms/s0108_convert_sorted_array_to_binary_search_tree/Solution.php +++ b/src/Algorithms/s0108_convert_sorted_array_to_binary_search_tree/Solution.php @@ -1,3 +1,5 @@ +$right) return null; - + if ($left > $right) return null; + /*3. Set median# as node*/ - $mid = intval(($left+$right)/2); + $mid = intval(($left + $right) / 2); $midNode = new TreeNode($num[$mid]); - + /*4. Set mid node's kids*/ - $midNode->left = self::makeTree($num, $left, $mid-1); - $midNode->right = self::makeTree($num, $mid+1, $right); - + $midNode->left = self::makeTree($num, $left, $mid - 1); + $midNode->right = self::makeTree($num, $mid + 1, $right); + /*5. Sends node back || Goes back to prev node*/ return $midNode; } diff --git a/src/Algorithms/s0109_convert_sorted_list_to_binary_search_tree/Solution.php b/src/Algorithms/s0109_convert_sorted_list_to_binary_search_tree/Solution.php index 310c855..a36ec63 100644 --- a/src/Algorithms/s0109_convert_sorted_list_to_binary_search_tree/Solution.php +++ b/src/Algorithms/s0109_convert_sorted_list_to_binary_search_tree/Solution.php @@ -1,3 +1,5 @@ +val = $val; } * } */ + /** * Definition for a binary tree node. * class TreeNode { @@ -30,7 +33,7 @@ function sortedListToBST($head) { return self::helper($lst, 0, count($lst) - 1); } - + function helper($lst, $start, $end) { if ($start > $end) { return null; diff --git a/src/Algorithms/s0110_balanced_binary_tree/Solution.php b/src/Algorithms/s0110_balanced_binary_tree/Solution.php index 3e8abb4..88d5ba1 100644 --- a/src/Algorithms/s0110_balanced_binary_tree/Solution.php +++ b/src/Algorithms/s0110_balanced_binary_tree/Solution.php @@ -1,3 +1,5 @@ +left == null ? 0 : self::checkDepth($root->left); $rh = $root->right == null ? 0 : self::checkDepth($root->right); - // Left subtree or right subtree is unbalanced + // Left subtree or right subtree is unbalanced if ($lh == -1 || $rh == -1) return -1; - // This tree is unbalanced + // This tree is unbalanced if ($lh - $rh > 1 || $lh - $rh < -1) return -1; - // Return depth of this tree + // Return depth of this tree return max($lh, $rh) + 1; } } diff --git a/src/Algorithms/s0111_minimum_depth_of_binary_tree/Solution.php b/src/Algorithms/s0111_minimum_depth_of_binary_tree/Solution.php index ca4d56b..cf205b2 100644 --- a/src/Algorithms/s0111_minimum_depth_of_binary_tree/Solution.php +++ b/src/Algorithms/s0111_minimum_depth_of_binary_tree/Solution.php @@ -1,3 +1,5 @@ +left == null) + else if ($root->left == null) return self::minDepth($root->right) + 1; - else if($root->right == null) + else if ($root->right == null) return self::minDepth($root->left) + 1; else return min(self::minDepth($root->left) + 1, self::minDepth($root->right) + 1); diff --git a/src/Algorithms/s0112_path_sum/Solution.php b/src/Algorithms/s0112_path_sum/Solution.php index ffe5f40..f7f1845 100644 --- a/src/Algorithms/s0112_path_sum/Solution.php +++ b/src/Algorithms/s0112_path_sum/Solution.php @@ -1,3 +1,5 @@ +left==null && $root->right==null) - { + if ($root->left == null && $root->right == null) { $s = $s + $root->val; if ($s == $sum) return true; @@ -34,7 +34,7 @@ function hasPathSumUtil($root, $sum, $s) $left = self::hasPathSumUtil($root->left, $sum, $s); $right = self::hasPathSumUtil($root->right, $sum, $s); - if($left || $right) + if ($left || $right) return true; return false; diff --git a/src/Algorithms/s0113_path_sum_ii/Solution.php b/src/Algorithms/s0113_path_sum_ii/Solution.php index e36acba..fe4e164 100644 --- a/src/Algorithms/s0113_path_sum_ii/Solution.php +++ b/src/Algorithms/s0113_path_sum_ii/Solution.php @@ -1,3 +1,5 @@ +val); - if($root->left==null && $root->right==null) - { + if ($root->left == null && $root->right == null) { $curSum = $curSum + $root->val; - if($sum==$curSum) - { + if ($sum == $curSum) { array_push($res, $temp); } } diff --git a/src/Algorithms/s0114_flatten_binary_tree_to_linked_list/Solution.php b/src/Algorithms/s0114_flatten_binary_tree_to_linked_list/Solution.php index 4924d1d..f95faa1 100644 --- a/src/Algorithms/s0114_flatten_binary_tree_to_linked_list/Solution.php +++ b/src/Algorithms/s0114_flatten_binary_tree_to_linked_list/Solution.php @@ -1,3 +1,5 @@ +left); self::flatten($root->right); - $left=$root->left; - $right=$root->right; + $left = $root->left; + $right = $root->right; $root->left = null; $root->right = $left; - $temp=$root; - while($temp->right != null){ + $temp = $root; + while ($temp->right != null) { $temp = $temp->right; } $temp->right = $right; diff --git a/src/Algorithms/s0115_distinct_subsequences/Solution.php b/src/Algorithms/s0115_distinct_subsequences/Solution.php index 64738fc..c255700 100644 --- a/src/Algorithms/s0115_distinct_subsequences/Solution.php +++ b/src/Algorithms/s0115_distinct_subsequences/Solution.php @@ -1,3 +1,5 @@ + 0; $j--){ - if ($s[$i] == $t[$j-1]){ - $match[$j] += $match[$j-1]; - } - } - } - return $match[$tLength]; + $tLength = strlen($t); + $match = array_fill(0, $tLength + 1, 0); + $match[0] = 1; + for ($i = 0; $i < strlen($s); $i++) { + for ($j = $tLength; $j > 0; $j--) { + if ($s[$i] == $t[$j - 1]) { + $match[$j] += $match[$j - 1]; + } + } + } + return $match[$tLength]; } } diff --git a/src/Algorithms/s0116_populating_next_right_pointers_in_each_node/Solution.php b/src/Algorithms/s0116_populating_next_right_pointers_in_each_node/Solution.php index 36abfaa..47ec7c4 100644 --- a/src/Algorithms/s0116_populating_next_right_pointers_in_each_node/Solution.php +++ b/src/Algorithms/s0116_populating_next_right_pointers_in_each_node/Solution.php @@ -1,3 +1,5 @@ +left!=null && $root->right!=null){ + } + + if ($root->left != null && $root->right != null) { $root->left->next = $root->right; } - - if($root->next!=null && $root->right!=null){ - $root->right->next=$root->next->left; + + if ($root->next != null && $root->right != null) { + $root->right->next = $root->next->left; } - + self::connect($root->left); self::connect($root->right); return $root; diff --git a/src/Algorithms/s0117_populating_next_right_pointers_in_each_node_ii/Solution.php b/src/Algorithms/s0117_populating_next_right_pointers_in_each_node_ii/Solution.php index 4c3cc40..5dd97d0 100644 --- a/src/Algorithms/s0117_populating_next_right_pointers_in_each_node_ii/Solution.php +++ b/src/Algorithms/s0117_populating_next_right_pointers_in_each_node_ii/Solution.php @@ -1,3 +1,5 @@ +left == null ? $temp->right : $temp->left; - } + while ($start != null) { + $temp = $start; + $prev = new Node(-1, null, null, null); + $start = null; - if ($temp->left != null) - { - $prev->next = $temp->left; - $prev = $temp->left; - } + while ($temp != null) { + if ($start == null) { + $start = $temp->left == null ? $temp->right : $temp->left; + } - if ($temp->right != null) - { - $prev->next = $temp->right; - $prev = $temp->right; - } + if ($temp->left != null) { + $prev->next = $temp->left; + $prev = $temp->left; + } - $temp = $temp->next; + if ($temp->right != null) { + $prev->next = $temp->right; + $prev = $temp->right; } + + $temp = $temp->next; } + } - return $root; + return $root; } } diff --git a/src/Algorithms/s0118_pascals_triangle/Solution.php b/src/Algorithms/s0118_pascals_triangle/Solution.php index 16fb754..260514c 100644 --- a/src/Algorithms/s0118_pascals_triangle/Solution.php +++ b/src/Algorithms/s0118_pascals_triangle/Solution.php @@ -1,3 +1,5 @@ +$rowIndex) + if ($row > $rowIndex) return; - + $numElem = $row + 1; $prev = 0; - for ($i=0; $i<$numElem; $i++) { - if ($i==$numElem-1) + for ($i = 0; $i < $numElem; $i++) { + if ($i == $numElem - 1) array_push($lvl, 1); else { // in-place replacement using temporary `prev` $curr = $lvl[$i]; - $lvl[$i] = $curr+$prev; + $lvl[$i] = $curr + $prev; $prev = $curr; // update prev for next iteration } } // recurse - self::getRowHelper($lvl, $row+1, $rowIndex); + self::getRowHelper($lvl, $row + 1, $rowIndex); } } diff --git a/src/Algorithms/s0120_triangle/Solution.php b/src/Algorithms/s0120_triangle/Solution.php index 32c2a27..a2faa7c 100644 --- a/src/Algorithms/s0120_triangle/Solution.php +++ b/src/Algorithms/s0120_triangle/Solution.php @@ -1,16 +1,18 @@ + $cur_max){ + $cur_max = $prices[$i]; + } else if ($prices[$i] > $cur_max) { $cur_max = $prices[$i]; } $cur_profit = $cur_max - $cur_min; - if($cur_profit > $max_profit) $max_profit = $cur_profit; + if ($cur_profit > $max_profit) $max_profit = $cur_profit; } return $max_profit; } diff --git a/src/Algorithms/s0122_best_time_to_buy_and_sell_stock_ii/Solution.php b/src/Algorithms/s0122_best_time_to_buy_and_sell_stock_ii/Solution.php index 0aed8a0..f4b476f 100644 --- a/src/Algorithms/s0122_best_time_to_buy_and_sell_stock_ii/Solution.php +++ b/src/Algorithms/s0122_best_time_to_buy_and_sell_stock_ii/Solution.php @@ -1,3 +1,5 @@ +maxSum; } - + function helper($root) { - if($root == null) return 0; + if ($root == null) return 0; $left = self::helper($root->left); $right = self::helper($root->right); $rootLeft = $left + $root->val; $rootRight = $right + $root->val; $ret = max(max($rootLeft, $rootRight), $root->val); $compSum = $root->val; - if($left > 0) $compSum += $left; - if($right > 0) $compSum += $right; + if ($left > 0) $compSum += $left; + if ($right > 0) $compSum += $right; $this->maxSum = max($this->maxSum, $compSum); return $ret; } diff --git a/src/Algorithms/s0125_valid_palindrome/Solution.php b/src/Algorithms/s0125_valid_palindrome/Solution.php index 6c63ac0..dea1076 100644 --- a/src/Algorithms/s0125_valid_palindrome/Solution.php +++ b/src/Algorithms/s0125_valid_palindrome/Solution.php @@ -1,3 +1,5 @@ + 96 && ord($c) < 123 || ord($c) > 47 && ord($c) < 58) return $c; if (ord($c) > 64 && ord($c) < 91) return chr(ord($c) + 32); diff --git a/src/Algorithms/s0128_longest_consecutive_sequence/Solution.php b/src/Algorithms/s0128_longest_consecutive_sequence/Solution.php index 54d20da..0af2aed 100644 --- a/src/Algorithms/s0128_longest_consecutive_sequence/Solution.php +++ b/src/Algorithms/s0128_longest_consecutive_sequence/Solution.php @@ -1,3 +1,5 @@ +val; - - if($root->left == null && $root->right == null) + + if ($root->left == null && $root->right == null) return $sum; - - return self::getSum($root->left,$sum) + self::getSum($root->right,$sum); - + + return self::getSum($root->left, $sum) + self::getSum($root->right, $sum); + } } diff --git a/src/Algorithms/s0130_surrounded_regions/Solution.php b/src/Algorithms/s0130_surrounded_regions/Solution.php index 50cefb6..bad7fcb 100644 --- a/src/Algorithms/s0130_surrounded_regions/Solution.php +++ b/src/Algorithms/s0130_surrounded_regions/Solution.php @@ -1,3 +1,5 @@ += 0) { - if ($board[$row - 1][$col] == 'O') { - self::color($board, $row - 1, $col); - } - } - if ($col + 1 < count($board[0])) { - if ($board[$row][$col + 1] == 'O') { - self::color($board, $row, $col + 1); - } - } - if ($col - 1 >= 0) { - if ($board[$row][$col - 1] == 'O') { - self::color($board, $row, $col - 1); - } - } - } + function color(&$board, $row, $col) { + $board[$row][$col] = 'V'; + if ($row + 1 < count($board)) { + if ($board[$row + 1][$col] == 'O') { + self::color($board, $row + 1, $col); + } + } + if ($row - 1 >= 0) { + if ($board[$row - 1][$col] == 'O') { + self::color($board, $row - 1, $col); + } + } + if ($col + 1 < count($board[0])) { + if ($board[$row][$col + 1] == 'O') { + self::color($board, $row, $col + 1); + } + } + if ($col - 1 >= 0) { + if ($board[$row][$col - 1] == 'O') { + self::color($board, $row, $col - 1); + } + } + } } diff --git a/src/Algorithms/s0131_palindrome_partitioning/Solution.php b/src/Algorithms/s0131_palindrome_partitioning/Solution.php index f2e8865..9fd0bf3 100644 --- a/src/Algorithms/s0131_palindrome_partitioning/Solution.php +++ b/src/Algorithms/s0131_palindrome_partitioning/Solution.php @@ -1,3 +1,5 @@ + $ratings[$i - 1]) - { + for ($i = 1; $i < $n; $i++) { + if ($ratings[$i] > $ratings[$i - 1]) { $candies[$i] = $candies[$i - 1] + 1; } - } + } - for($i = $n - 1; $i > 0; $i--) - { - if($ratings[$i - 1] > $ratings[$i] && $candies[$i - 1] <= $candies[$i]) - { + for ($i = $n - 1; $i > 0; $i--) { + if ($ratings[$i - 1] > $ratings[$i] && $candies[$i - 1] <= $candies[$i]) { $candies[$i - 1] = $candies[$i] + 1; } - } + } - foreach($candies as $candy) - $sum += $candy; + foreach ($candies as $candy) + $sum += $candy; - return $sum; + return $sum; } } diff --git a/src/Algorithms/s0136_single_number/Solution.php b/src/Algorithms/s0136_single_number/Solution.php index ee9989d..6592fd7 100644 --- a/src/Algorithms/s0136_single_number/Solution.php +++ b/src/Algorithms/s0136_single_number/Solution.php @@ -1,3 +1,5 @@ +next; + // First round: make copy of each node, + // and link them together side-by-side in a single list. + while ($iter != null) { + $next = $iter->next; - $copy = new Node($iter->val, null, null); - $iter->next = $copy; - $copy->next = $next; + $copy = new Node($iter->val, null, null); + $iter->next = $copy; + $copy->next = $next; - $iter = $next; - } + $iter = $next; + } - // Second round: assign random pointers for the copy nodes. - $iter = $head; - while ($iter != null) { - if ($iter->random != null) { - $iter->next->random = $iter->random->next; + // Second round: assign random pointers for the copy nodes. + $iter = $head; + while ($iter != null) { + if ($iter->random != null) { + $iter->next->random = $iter->random->next; + } + $iter = $iter->next->next; } - $iter = $iter->next->next; - } - // Third round: restore the original list, and extract the copy list. - $iter = $head; - $pseudoHead = new Node(0, null, null); - $copy; - $copyIter = $pseudoHead; + // Third round: restore the original list, and extract the copy list. + $iter = $head; + $pseudoHead = new Node(0, null, null); + $copy; + $copyIter = $pseudoHead; - while ($iter != null) { - $next = $iter->next->next; + while ($iter != null) { + $next = $iter->next->next; - // extract the copy - $copy = $iter->next; - $copyIter->next = $copy; - $copyIter = $copy; + // extract the copy + $copy = $iter->next; + $copyIter->next = $copy; + $copyIter = $copy; - // restore the original list - $iter->next = $next; + // restore the original list + $iter->next = $next; - $iter = $next; - } + $iter = $next; + } - return $pseudoHead->next; + return $pseudoHead->next; } } diff --git a/src/Algorithms/s0139_word_break/Solution.php b/src/Algorithms/s0139_word_break/Solution.php index 4cf332f..327888d 100644 --- a/src/Algorithms/s0139_word_break/Solution.php +++ b/src/Algorithms/s0139_word_break/Solution.php @@ -1,3 +1,5 @@ +next != null){ + while ($fast != null && $fast->next != null) { $fast = $fast->next->next; $slow = $slow->next; } - + $next = null; $curr = $slow; $prev = null; - while($curr != null){ + while ($curr != null) { $next = $curr->next; $curr->next = $prev; $prev = $curr; $curr = $next; } - + $temp; - while($prev != null && $head->next != null){ + while ($prev != null && $head->next != null) { $temp = $head->next; $head->next = $prev; $head = $temp; diff --git a/src/Algorithms/s0144_binary_tree_preorder_traversal/Solution.php b/src/Algorithms/s0144_binary_tree_preorder_traversal/Solution.php index 66dcdeb..356da74 100644 --- a/src/Algorithms/s0144_binary_tree_preorder_traversal/Solution.php +++ b/src/Algorithms/s0144_binary_tree_preorder_traversal/Solution.php @@ -1,3 +1,5 @@ +val); array_push($stack, $node->right); $node = $node->left; - } + } } return $list; } diff --git a/src/Algorithms/s0145_binary_tree_postorder_traversal/Solution.php b/src/Algorithms/s0145_binary_tree_postorder_traversal/Solution.php index 5cd8369..bdbb314 100644 --- a/src/Algorithms/s0145_binary_tree_postorder_traversal/Solution.php +++ b/src/Algorithms/s0145_binary_tree_postorder_traversal/Solution.php @@ -1,3 +1,5 @@ +key = $key; $this->val = $val; @@ -24,7 +27,7 @@ function __construct($capacity) { $this->tail->prev = $this->head; $this->map = []; } - + /** * @param Integer $key * @return Integer @@ -38,7 +41,7 @@ function get($key) { } return -1; } - + /** * @param Integer $key * @param Integer $value @@ -64,12 +67,12 @@ function put($key, $value) { $this->currentCapacity++; } } - + function removeNode($node) { $node->prev->next = $node->next; $node->next->prev = $node->prev; } - + function addToTail($node) { $this->tail->prev->next = $node; $node->prev = $this->tail->prev; diff --git a/src/Algorithms/s0147_insertion_sort_list/Solution.php b/src/Algorithms/s0147_insertion_sort_list/Solution.php index 0f6e42d..2004cf8 100644 --- a/src/Algorithms/s0147_insertion_sort_list/Solution.php +++ b/src/Algorithms/s0147_insertion_sort_list/Solution.php @@ -1,3 +1,5 @@ +next == null ) return $head; + if ($head == null || $head->next == null) return $head; $tmp; - $k; $z; + $k; + $z; for ($start = $head; $start->next != null; $start = $start->next) { $tmp = $start->next; $k = $tmp->val; diff --git a/src/Algorithms/s0148_sort_list/Solution.php b/src/Algorithms/s0148_sort_list/Solution.php index 928212b..914f3c6 100644 --- a/src/Algorithms/s0148_sort_list/Solution.php +++ b/src/Algorithms/s0148_sort_list/Solution.php @@ -1,3 +1,5 @@ +next != null) { + while ($fast != null && $fast->next != null) { $pre = $slow; $slow = $slow->next; $fast = $fast->next->next; @@ -30,7 +32,7 @@ function sortList($head) { $cur = $res; while ($first != null || $second != null) { if ($first == null) { - $cur->next= $second; + $cur->next = $second; break; } else if ($second == null) { $cur->next = $first; diff --git a/src/Algorithms/s0149_max_points_on_a_line/Solution.php b/src/Algorithms/s0149_max_points_on_a_line/Solution.php index 2ae412d..33fa181 100644 --- a/src/Algorithms/s0149_max_points_on_a_line/Solution.php +++ b/src/Algorithms/s0149_max_points_on_a_line/Solution.php @@ -1,3 +1,5 @@ +y - $points[$i]->y; $x = $points[$j]->x - $points[$i]->x; - + if ($x == 0 && $y == 0) { - $duplicated++; - if ($isMaxChanged == true) { - $max++; - } else if ($max < $duplicated) { - $max = $duplicated; - } - + $duplicated++; + if ($isMaxChanged == true) { + $max++; + } else if ($max < $duplicated) { + $max = $duplicated; + } + } else { - $gcd = self::getGCD($y,$x); - if ($gcd != 0) { - $y = intval($y / $gcd); - $x = intval($x / $gcd); - $k = $y."/".$x; - if (array_key_exists($k, $amount)) { - $n = $amount[$k]; - $amount[$k] = $n+1; - if ($max < $n+1+$duplicated) { - $max = $n+1+$duplicated; - $isMaxChanged = true; - } - } else { - $amount[$k] = 1; - if ($max < 1+$duplicated) { - $max = 1+$duplicated; - $isMaxChanged = true; - } - } - } + $gcd = self::getGCD($y, $x); + if ($gcd != 0) { + $y = intval($y / $gcd); + $x = intval($x / $gcd); + $k = $y . "/" . $x; + if (array_key_exists($k, $amount)) { + $n = $amount[$k]; + $amount[$k] = $n + 1; + if ($max < $n + 1 + $duplicated) { + $max = $n + 1 + $duplicated; + $isMaxChanged = true; + } + } else { + $amount[$k] = 1; + if ($max < 1 + $duplicated) { + $max = 1 + $duplicated; + $isMaxChanged = true; + } + } + } } } $duplicated = 0; $isMaxChanged = false; - + } - return $max+1; + return $max + 1; } } - + //horizontal lines make x=0 & y=1 //vertical lines make x=1 & y=0 //same position points should not invoke this function whick make x=0 & y=0 //other points return the gcd function getGCD($y, $x) { - if ($x == 0) { - if ($y == 0) { - return 0;//same point - } else { - return $y;//horizontal lines - } - } else { - //normal case and the vertical lines - if ($y%$x != 0) { - return self::getGCD($x,$y%$x); - } else { - return $x; - } - } + if ($x == 0) { + if ($y == 0) { + return 0;//same point + } else { + return $y;//horizontal lines + } + } else { + //normal case and the vertical lines + if ($y % $x != 0) { + return self::getGCD($x, $y % $x); + } else { + return $x; + } + } } } diff --git a/src/Algorithms/s0150_evaluate_reverse_polish_notation/Solution.php b/src/Algorithms/s0150_evaluate_reverse_polish_notation/Solution.php index 859a42f..053e1ed 100644 --- a/src/Algorithms/s0150_evaluate_reverse_polish_notation/Solution.php +++ b/src/Algorithms/s0150_evaluate_reverse_polish_notation/Solution.php @@ -1,3 +1,5 @@ += 0; $i--){ - if(strlen(trim($words[$i])) != 0){ + + for ($i = count($words) - 1; $i >= 0; $i--) { + if (strlen(trim($words[$i])) != 0) { $sb .= trim($words[$i]); $sb .= " "; } diff --git a/src/Algorithms/s0152_maximum_product_subarray/Solution.php b/src/Algorithms/s0152_maximum_product_subarray/Solution.php index 74e65d4..56b1283 100644 --- a/src/Algorithms/s0152_maximum_product_subarray/Solution.php +++ b/src/Algorithms/s0152_maximum_product_subarray/Solution.php @@ -1,3 +1,5 @@ +=$nums[$l]) $l=$m; - else $r=$m; + while ($l < $r - 1) {//now we are bold to handle it as there must be a steep and the minimum is the right one. + $m = intval($l + ($r - $l) / 2); + if ($nums[$m] >= $nums[$l]) $l = $m; + else $r = $m; } return $nums[$r]; } diff --git a/src/Algorithms/s0162_find_peak_element/Solution.php b/src/Algorithms/s0162_find_peak_element/Solution.php index 62a9dbf..489eea8 100644 --- a/src/Algorithms/s0162_find_peak_element/Solution.php +++ b/src/Algorithms/s0162_find_peak_element/Solution.php @@ -1,3 +1,5 @@ +=2){ - if($nums[count($nums)-1]>$nums[count($nums)-2])return count($nums)-1; + if ($nums == null || count($nums) <= 1) return 0; + + if (count($nums) >= 2) { + if ($nums[count($nums) - 1] > $nums[count($nums) - 2]) return count($nums) - 1; } - - for($i=1;$i$nums[$i-1]&&$nums[$i]>$nums[$i+1])return $i; + + for ($i = 1; $i < count($nums) - 1; $i++) { + if ($nums[$i] > $nums[$i - 1] && $nums[$i] > $nums[$i + 1]) return $i; } - + return 0; } } diff --git a/src/Algorithms/s0164_maximum_gap/Solution.php b/src/Algorithms/s0164_maximum_gap/Solution.php index 5a7bb82..2639b37 100644 --- a/src/Algorithms/s0164_maximum_gap/Solution.php +++ b/src/Algorithms/s0164_maximum_gap/Solution.php @@ -1,3 +1,5 @@ +$num ? $num : $min; + $max = $max < $num ? $num : $max; + $min = $min > $num ? $num : $min; } // the size of bucket must > 1 $bucketSize = intval(max(1, ($max - $min) / (count($nums) - 1))); - $bucketNum = intval(($max-$min) / $bucketSize + 1); + $bucketNum = intval(($max - $min) / $bucketSize + 1); $buckets = array_fill(0, $bucketNum, null); - for ($i=0; $irightOpen; - for ($i=1; $iusedFlag == false) { continue; } - $maxGap = max($maxGap, $buckets[$i]->leftClose-$preRightOpen); + $maxGap = max($maxGap, $buckets[$i]->leftClose - $preRightOpen); $preRightOpen = $buckets[$i]->rightOpen; } diff --git a/src/Algorithms/s0165_compare_version_numbers/Solution.php b/src/Algorithms/s0165_compare_version_numbers/Solution.php index 5937ef3..5fcf5f3 100644 --- a/src/Algorithms/s0165_compare_version_numbers/Solution.php +++ b/src/Algorithms/s0165_compare_version_numbers/Solution.php @@ -1,3 +1,5 @@ + $n2) return 1; if ($n1 < $n2) return -1; $n1 = $n2 = 0; - $i1++; $i2++; + $i1++; + $i2++; } return 0; } diff --git a/src/Algorithms/s0166_fraction_to_recurring_decimal/Solution.php b/src/Algorithms/s0166_fraction_to_recurring_decimal/Solution.php index 77427f6..544772e 100644 --- a/src/Algorithms/s0166_fraction_to_recurring_decimal/Solution.php +++ b/src/Algorithms/s0166_fraction_to_recurring_decimal/Solution.php @@ -1,3 +1,5 @@ + 0 && $deno1 < 0 || $num1 < 0 && $deno1 > 0; - $ret = $neg ? "-":""; + $ret = $neg ? "-" : ""; $num = abs($num1); $deno = abs($deno1); - - - $p1 = intval($num/$deno); - $remain = $num%$deno; - if($remain == 0) return $ret . $p1; - + + + $p1 = intval($num / $deno); + $remain = $num % $deno; + if ($remain == 0) return $ret . $p1; + $map = []; $sb = ""; - + $start = -1; $end = -1; - $map[$remain] = 0; + $map[$remain] = 0; echo($sb); - while($remain != 0) { + while ($remain != 0) { $remain *= 10; - while($remain < $deno) { + while ($remain < $deno) { $sb .= '0'; $map[$remain] = strlen($sb); $remain *= 10; } - - $res = intval($remain/$deno); + + $res = intval($remain / $deno); $sb = $sb . chr($res + ord('0')); - + $remain %= $deno; - if($remain == 0) break; - + if ($remain == 0) break; + $len = strlen($sb); - if(array_key_exists($remain, $map)) { + if (array_key_exists($remain, $map)) { $start = $map[$remain]; break; } else { $map[$remain] = $len; } } - + $ret = $ret . $p1 . "."; - if($start == -1) { + if ($start == -1) { $ret .= $sb; } else { $ret = $ret . substr($sb, 0, $start) . "(" . substr($sb, $start) . ")"; } - + return $ret; } } diff --git a/src/Algorithms/s0167_two_sum_ii_input_array_is_sorted/Solution.php b/src/Algorithms/s0167_two_sum_ii_input_array_is_sorted/Solution.php index 5828702..46508aa 100644 --- a/src/Algorithms/s0167_two_sum_ii_input_array_is_sorted/Solution.php +++ b/src/Algorithms/s0167_two_sum_ii_input_array_is_sorted/Solution.php @@ -1,3 +1,5 @@ + 0) { + while ($n > 0) { $sb .= $mapping [--$n % 26]; //Since for a base 26 the numbers would be from 0 to 25. Deducting 1 $n = intval($n / 26); } diff --git a/src/Algorithms/s0169_majority_element/Solution.php b/src/Algorithms/s0169_majority_element/Solution.php index 3ea48be..ca7e4d1 100644 --- a/src/Algorithms/s0169_majority_element/Solution.php +++ b/src/Algorithms/s0169_majority_element/Solution.php @@ -1,3 +1,5 @@ +=0;$i--) - { - - $sum=$sum+(ord($s[$i])-64)*$jinzhi; - $jinzhi=$jinzhi*26; + $len = strlen($s); + $jinzhi = 1; + $sum = 0; + for ($i = $len - 1; $i >= 0; $i--) { + + $sum = $sum + (ord($s[$i]) - 64) * $jinzhi; + $jinzhi = $jinzhi * 26; } return $sum; } diff --git a/src/Algorithms/s0172_factorial_trailing_zeroes/Solution.php b/src/Algorithms/s0172_factorial_trailing_zeroes/Solution.php index a760e87..e6f22b7 100644 --- a/src/Algorithms/s0172_factorial_trailing_zeroes/Solution.php +++ b/src/Algorithms/s0172_factorial_trailing_zeroes/Solution.php @@ -1,3 +1,5 @@ += 5){ + while ($n >= 5) { $n = intval($n / 5); $res += $n; } diff --git a/src/Algorithms/s0174_dungeon_game/Solution.php b/src/Algorithms/s0174_dungeon_game/Solution.php index 41a495c..efaee94 100644 --- a/src/Algorithms/s0174_dungeon_game/Solution.php +++ b/src/Algorithms/s0174_dungeon_game/Solution.php @@ -1,3 +1,5 @@ += 1 ? 1 : 1-$val; + return $val >= 1 ? 1 : 1 - $val; } - + function solve(&$dungeon, $i, $j) { - if($i == count($dungeon)-1 && $j == count($dungeon[0])-1) return $dungeon[$i][$j]; - if($i == count($dungeon)) return -2147483647; - if($j == count($dungeon[0])) return -2147483647; - - if($visited[$i][$j]) { + if ($i == count($dungeon) - 1 && $j == count($dungeon[0]) - 1) return $dungeon[$i][$j]; + if ($i == count($dungeon)) return -2147483647; + if ($j == count($dungeon[0])) return -2147483647; + + if ($visited[$i][$j]) { return $dp[$i][$j]; } - - $val = min($dungeon[$i][$j] + max(self::solve($dungeon, $i+1, $j), self::solve($dungeon, $i, $j+1)), $dungeon[$i][$j]); - + + $val = min($dungeon[$i][$j] + max(self::solve($dungeon, $i + 1, $j), self::solve($dungeon, $i, $j + 1)), $dungeon[$i][$j]); + $dp[$i][$j] = $val; $visited[$i][$j] = true; - + return $val; } } diff --git a/src/Algorithms/s0179_largest_number/Solution.php b/src/Algorithms/s0179_largest_number/Solution.php index 13efc70..036894c 100644 --- a/src/Algorithms/s0179_largest_number/Solution.php +++ b/src/Algorithms/s0179_largest_number/Solution.php @@ -1,32 +1,34 @@ +key = $key; $this->i = $i; @@ -27,7 +30,7 @@ function shortestPathAllKeys($grid) { if ($c >= 'A' && $c <= 'F') { $success |= 1 << (ord($c) - ord('A')); } - + if ($c == '@') { $startI = $i; $startJ = $j; @@ -57,11 +60,11 @@ function shortestPathAllKeys($grid) { if ($c >= 'a' && $c <= 'f') { $nextKey = $key | (1 << (ord($c) - ord('a'))); } - + if ($c >= 'A' && $c <= 'F') { if (($nextKey & (1 << (ord($c) - ord('A')))) == 0) continue; } - + if ($path + 1 < $dist[$nextKey][$xx][$yy]) { $dist[$nextKey][$xx][$yy] = $path + 1; array_unshift($queue, new Status($nextKey, $xx, $yy)); diff --git a/src/Algorithms/s0973_k_closest_points_to_origin/Solution.php b/src/Algorithms/s0973_k_closest_points_to_origin/Solution.php index 695fc82..a1bad58 100644 --- a/src/Algorithms/s0973_k_closest_points_to_origin/Solution.php +++ b/src/Algorithms/s0973_k_closest_points_to_origin/Solution.php @@ -1,3 +1,5 @@ +