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

题目描述

请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。

假设字符串中只包含从 az的字符。

解法

动态规划。

res[i] 表示以 s[i] 字符结尾的最长不重复字符串的长度。判断 s[i]

  • s[i] 在前面没出现过,那么 res[i] = res[i - 1] + 1
  • s[i] 在前面有出现过,判断它上一次出现的位置 indexi 的距离 dres[i - 1] 的大小关系:
    • d <= res[i - 1],说明它被包含在 res[i - 1] 构成的子串中,那么 res[i] = d
    • d > res[i - 1],说明它在 res[i - 1] 构成的子串的左侧,那么 res[i] = res[i - 1] + 1

需要用一个数组 t 记录一下当前出现的字符在哪个位置。

  1. /**
  2. * @author bingo
  3. * @since 2018/12/8
  4. */
  5. class Solution {
  6. /**
  7. * 最长不含重复字符的子字符串
  8. *
  9. * @param s 字符串
  10. * @return 最长不重复字符子串
  11. */
  12. public int longestSubstringWithoutDuplication(String s) {
  13. if (s == null || s.length() == 0) {
  14. return 0;
  15. }
  16. char[] chars = s.toCharArray();
  17. int[] t = new int[26];
  18. for (int i = 0; i < 26; ++i) {
  19. t[i] = -1;
  20. }
  21. t[chars[0] - 'a'] = 0;
  22. int n = chars.length;
  23. int[] res = new int[n];
  24. res[0] = 1;
  25. int max = res[0];
  26. for (int i = 1; i < n; ++i) {
  27. int index = t[chars[i] - 'a'];
  28. int d = i - index;
  29. res[i] = (index == -1 || d > res[i - 1])
  30. ? res[i - 1] + 1
  31. : d;
  32. t[chars[i] - 'a'] = i;
  33. max = Math.max(max, res[i]);
  34. }
  35. return max;
  36. }
  37. }

测试用例

  1. 功能测试(包含多个字符的字符串;只有一个字符的字符串;所有字符都唯一的字符串;所有字符都相同的字符串);
  2. 特殊输入测试(空字符串)。

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