Status message

Maintenant, vous regardez: 3. Longest Substring Without Repeating Characters

3. Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Example 1:

  1. Input: "abcabcbb"
  2. Output: 3
  3. Explanation: The answer is "abc", with the length of 3.

Example 2:

  1. Input: "bbbbb"
  2. Output: 1
  3. Explanation: The answer is "b", with the length of 1.

Example 3:

  1. Input: "pwwkew"
  2. Output: 3
  3. Explanation: The answer is "wke", with the length of 3.
  4. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

Structure:

  1. class Solution {
  2.  
  3. /**
  4.   * @param String $s
  5.   * @return Integer
  6.   */
  7. function lengthOfLongestSubstring($s) {
  8.  
  9. }
  10. }

Solution:

  1. class Solution {
  2.  
  3. /**
  4.   * @param String $s
  5.   * @return Integer
  6.   */
  7. function lengthOfLongestSubstring($s) {
  8. if (strlen($s)==0) return 0;
  9. $map = [];
  10. $max = 0;
  11. for ($i=0, $j=0; $i < strlen($s); ++$i) {
  12. if (array_key_exists($s[$i], $map)){
  13. $j = max($j, $map[$s[$i]] + 1);
  14. }
  15. echo $j . "\n";
  16. $map[$s[$i]] = $i;
  17. print_r($map);
  18. $max = max($max, $i - $j + 1);
  19. }
  20. return $max;
  21. }
  22. }
  23.  
  24. $instance = new Solution();
  25.  
  26. print $instance->lengthOfLongestSubstring('abcabcbb');

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
2 + 10 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.