![]() |
| "踏上LeetCode解題之路,順手紀錄一下PHP練功的過程囉。這是第二篇~~" |
Longest Substring Without Repeating Characters - LeetCode
題目要求
Given a string
s, find the length of the longest substring without repeating characters.
思考過程
- 先取得字串長度strlen($s)
- ...
❎
class Solution {
/**
* @param String $s
* @return Integer
*/
function lengthOfLongestSubstring($s) {
$x= strlen($s);
$text = "";
$number=0;
$list = [0];
for($i=0; $i<$x; $i++){
if ($s[$i] != $s[$i+1] && !str_contains($text, $s[$i]) ){
$text= "$text+$s[$i]";
$number++;
$list[$i]= $number;
/* $list=[1,2,3....]*/
}elseif($s[$i] == $s[$i+1]){
/*echo $s[$i];*/
$number=0;
}else{
echo '';
}
}
參考解答
class Solution {
/**
* @param String $s
* @return Integer
*/
function lengthOfLongestSubstring($s) {
if(strlen($s) == 0) return 0;
$strarr = str_split($s);
$substr = [];
$max_len = 1;
foreach($strarr as $i) {
$found = array_search($i,$substr) ;
if($found === false) {
$substr[] = $i;
if(count($substr) > $max_len){
$max_len = count($substr);
}
} else {
$substr[] = $i;
$found += 1;
$sliced_array = array_slice($substr, $found);
$substr = $sliced_array;
}
}
return $max_len;
}
}
