-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestSubstring.php
More file actions
36 lines (29 loc) · 811 Bytes
/
longestSubstring.php
File metadata and controls
36 lines (29 loc) · 811 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
/*
Length of the longest substring without repeating characters
*/
function longestSubstring($string) {
$longestSubstring = '';
$visited = array();
$tempLongestSubstring = '';
$length = strlen($string);
$prev_index = 0;
for($i=0;$i<$length;$i++) {
if(isset($visited[$string[$i]])) {
if(strlen($longestSubstring) < strlen($tempLongestSubstring)) {
$longestSubstring = $tempLongestSubstring;
}
$tempLongestSubstring = substr($tempLongestSubstring,$visited[$i]-$prev_index);
$prev_index = $visited[$i]+1;
} else {
$tempLongestSubstring .= $string[$i];
}
$visited[$string[$i]] = $i;
}
if(strlen($longestSubstring) < strlen($tempLongestSubstring)) {
$longestSubstring = $tempLongestSubstring;
}
return $longestSubstring;
}
echo longestSubstring("ABDEFGABEF");
?>