leetcode : Longest substring without repeating characters

来源:互联网 发布:广西老年大学网络报名 编辑:程序博客网 时间:2024/06/05 05:16

  这是我第一次发微博,之前一直都是在有道云笔记上记录平时的学习。今天看到CSDN的博客平台如此强大,还支持latex公式(),在latex下输入公式真的很爽。 从今天开始打算一点点转移到博客平台,和更多的人分享,学习。
  最近在刷leetcode, 感觉有点吃力,好多思路还是摸不着头脑。不过我相信多看,多练,多思考,肯定会越来越顺的。不扯没用的了,下面直接上题:
  题目描述
  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.
  分析
  在一个给定字符串中查找无重复字符的最长子串的长度。可以定义一个空的字符串str, 然后从头遍历给定字符串s, 每遍历一个字符c则在str中查找,看c是否在str中存在,如果存在则将str中从起始字符到字符c的子串删除,然后将此遍历字符在插入到str的后面。如果在str中不存在c, 则直接将c插入到str的后面。整个过程中保存str字符串长度的最大值。

    class Solution{    public:        int lengthOfLongestSubstring(string s){            if(s.size() < 2)                return s.size();            string str = "";            int num = 0;            str += s[0];            for(int i=0; i<str.size(); ++i){                int pos = str.find(s[i]);                if(pos == string::npos){                    str += s[i];                }                else{                    if(str.size() > num){                        num = str.size();                    }                    str.erase(0, pos+1);                    str += s[i];                }            }            if(str.size() > num){                num = str.size();            }            return num;        }    };

以上算法是我自己想出来的,对于每一个遍历到的字符都需要在str中find一遍,比较耗时。下面是leetcode题解上的答案,它使用了一个大小为26的数组,记录每一个字符是否出现过,以及出现的位置。因此遍历每一个字符时,只需要在数组中看此字符的位置是否已经赋过值,如果已经有值,则表示重复。那么下一次计算字符串长度的起始位置就从此重复字符的位置的下一个位置开始。遍历过程中保存不重复子串长度的最大值。

class Solution{public:    int lengthOfLongestSubstring(string s){        const int ASCII_MAX = 26;        int last[ASCII_MAX];  //记录字符串上次出现的位置        int start = 0;  //记录当前子串的起始位置        fill(last, last+ASCII_MAX, -1);        int max_len = 0;        for(int i=0; i<s.size(); s++){            if(last[s[i]-'a'] > start){                max_len = max(max_len, i-start);                start = last[s[i]-'a'] +1;            }            last[s[i]-'a'] = i;        }        return max(max_len, (int)s.size()-start);   //最后一次    }};
0 0
原创粉丝点击