leetcode Longest Substring Without Repeating Characters

来源:互联网 发布:林珊珊淘宝店铺首页 编辑:程序博客网 时间:2024/06/13 16:42

题目

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.
题目来源:https://leetcode.com/problems/longest-substring-without-repeating-characters/

分析

题目不难理解,就是找一个子串,这个子串里面没有重复的字符,返回其长度。判断一个字符串里面有没有重复的字符,一个简单的方法是借助hash table,因为c++里面的字符最多也就256个,其实源字符串中都是英文字母,hash table的长度为52就可以了。
这让我联想到了之前的一个面试题,根据年龄大小对公司员工排序。这样的话就可以借助hash table,因为人类的年龄还没有超过150岁的哈,使用长度为150的hash table就已经绰绰有余了。然后遍历hash table,对年龄进行排序就很方便了。这比快速排序、堆排序之类的都要方便了。
言归正传,设置两个指针,初始位置pl = 0, pr = 1.如果指针之间表示的子串有重复字符,则pl向右移动,如果没有重复字符,则pr向右移动。

代码

class Solution {public:    bool isRepeat(string str){        int hash_help[256] = {0};        int len = str.length();        for(int i = 0; i < len; i++){            hash_help[str[i]]++;        }        for(int i = 0; i < 256; i++){            if(hash_help[i] >= 2)                return true;        }        return false;    }    int lengthOfLongestSubstring(string s) {        int len = s.length();        if(len < 2)            return len;         int pl = 0, pr = 1;        int max_len = 1;        while(pl <= pr && pr < len){            string sub = s.substr(pl, pr-pl+1);            if(!isRepeat(sub)){                if(pr-pl+1 > max_len)                    max_len = pr-pl+1;                pr++;            }            else{                pl++;            }        }        return max_len;    }};
0 0
原创粉丝点击