当前位置:  首页>> 技术小册>> 数据结构与算法(中)

难度: Medium

刷题内容

内容描述

  1. 给定一个字符串,求最长子字符串的长度,不重复字符。
  2. Example 1:
  3. Input: "abcabcbb"
  4. Output: 3
  5. Explanation: The answer is "abc", with the length of 3.
  6. Example 2:
  7. Input: "bbbbb"
  8. Output: 1
  9. Explanation: The answer is "b", with the length of 1.
  10. Example 3:
  11. Input: "pwwkew"
  12. Output: 3
  13. Explanation: The answer is "wke", with the length of 3.
  14. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

解题方案

思路 1
**- 时间复杂度: O(N)**- 空间复杂度: O(1)**

  1. class Solution {
  2. public int lengthOfLongestSubstring(String s) {
  3. int stIdx = 0, maxLen = 0;
  4. int arr[] = new int[128];
  5. for(int i=0;i<s.length();i++){
  6. stIdx = Math.max(arr[s.charAt(i)],stIdx);
  7. maxLen = Math.max(maxLen, i-stIdx+1);
  8. arr[s.charAt(i)] = i+1;
  9. }
  10. return maxLen;
  11. }
  12. }

该分类下的相关小册推荐: