zoukankan      html  css  js  c++  java
  • Longest Substring Without Repeating Characters

    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.

    思路:本题找出字符串中最长的不包含相同的字符的子字符串不包含相同的字符。可以使用hash表来解决这道题。主要思路就是使用两个头尾指针,尾指针不断往后搜索,当该字符在前面出现过了,记录字符的长度和最长结果,此时头指针不断往后搜索,同时记录的长度count要减一,直到头指针指向的字符与尾指针相同时结束搜索,同时头指针向后移动一位,记录访问过的字符,长度count加一。最后优化最长结果。

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            int n=s.size();
            if(n<=1)
                return n;
            int result=0;
            int count=0;
            int begin=0;
            vector<bool> charTable(256,false);
            for(int i=0;i<n;i++)
            {
                if(charTable[s[i]]==false)//前面字符没有出现过,false表示没有出现过。
                {
                    charTable[s[i]]=true;
                    count++;
                }
                else
                {
                    result=max(result,count);
                    while(true)
                    {
                        charTable[s[begin]]=false;
                        count--;
                        if(s[begin]==s[i])
                            break;
                        begin++;
                    }
                    begin++;
                    charTable[s[i]]=true;
                    count++;
                }
            }
            result=max(result,count);
            return result;
        }
    };

       这道题也可以使用STL中的hash_map解决。至于如何实现,待我熟悉hash_map便可进行。

  • 相关阅读:
    基于jdk8+selenium3+chrome86的UI自动化测试
    服务器虚拟化管理解决方案PVM发送c+a+d组合键
    web端测试技巧记录
    redis-基本数据类型及应用场景
    idea编译时报GC overhead limit exceeded
    cmd常用命令
    @property和@属性.setter的用法
    游陶然亭记
    山城
    记京都春节
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3729876.html
Copyright © 2011-2022 走看看