LeetCode算法问题7 —— Longest Substring Without Repeating Characters

来源:互联网 发布:携程php招聘 编辑:程序博客网 时间:2024/06/06 08:41

问题描述
这里写图片描述

简单来说,就是找一个字符串中最长的不存在重复字母的子串长度

自然遍历字符串一遍是不可避免的,自然,我的想法就是建立一个临时字符串变量temp存储当前遍历到的无重复字母的字符串,在对给定字符串进行遍历的时候,可能会出现几种情况:

  1. 不是重复字母,则temp将其加上
  2. 是重复字母,则:
    a. 首先比较当前temp长度和目前所遇到的最长长度哪个大,若是temp较长则替换
    b. 如果重复字母出现在temp的中间,则中间及以前的字符串都必须剔除,新的temp是重复字母之后的子串与重复字母的合
    c. 如果重复字母出现在末位,则temp元素全部替换

下面是源代码:

int lengthOfLongestSubstring(string s) {        string temp;        int biggestLength = 0;        size_t pos;        for (int i = 0; i < s.size(); i++) {            pos = temp.find(s[i]);            if (pos != string::npos) {                if (temp.size() > biggestLength)                    biggestLength = temp.size();                /* The repeating character isn't in the end of the string "answer" */                if (pos != temp.size() - 1) {                    temp = temp.substr(pos + 1) + s[i];                } else {                    temp = s[i];                }            } else {                temp += s[i];            }        }        if (temp.size() > biggestLength)            biggestLength = temp.size();        return biggestLength;    }

时间复杂度是O(n),暂且没有找到更好的办法,希望能获取大家的建议

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