LeetCode算法题——Longest Substring Without Repeating Characters

来源:互联网 发布:bluehost域名跳转 编辑:程序博客网 时间:2024/06/01 07:33

题目概述

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

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

分析

使用桶的思想,将每一个字符对应为一个桶。遍历字符串,桶中记录的的是每一个字符可能作为最长子字符串时的下标。置第一个字符对应的桶为起始下标,因为所有桶中原来的值都是-1,只有在遇到重复的字母的时候,才会导致桶中的值大于起始下标的情况,这时候只需要重新指定起始下标即可。同时以当前遍历的字符下标减去起始坐标就是当前最大子字符串的长度。

例如以字符串abcabcbb为例,一开始起始下标为-1,dict[‘a’] = 0,dict[‘b’] = 1, dict[‘c’] = 2,在下标i = 3时,访问dict[‘a’]出现了桶值0 > -1大于下标的情况,这说明遇到了重复字母,因此需要对起始下标进行重新赋值,即当前的遍历下标3。按照此过程即可实现算法。

整个算法只遍历了一次数组,同时也并未调用较复杂的函数,时间复杂度为O(n),而空间复杂度更是仅为常量级O(1),精炼高效。

int lengthOfLongestSubstring(string s) {    vector<int> dict(256, -1);    int result = 0, start = -1;    for (int i = 0; i != s.length(); i++) {        if (dict[s[i]] > start) start = dict[s[i]];        dict[s[i]] = i;        result = max(result, i - start);    }    return result;}

总结

· 在处理字符串,又涉及到非重复性的问题上,有时候可以利用桶的思想,因为字符的种类数目是有限的,只需要一个长度为256的数组既可以完成桶的构造。

· 起始下标变量可以形象地理解成为一个指针,这种思想在涉及遍历,研究顺序的题目中十分形象直观。

阅读全文
0 0
原创粉丝点击