zoukankan      html  css  js  c++  java
  • LeetCode(3)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.
    提示标签: hashtable 、 Two Pointers 、 String

    分析:

    该题目是一个求最长连续子串的长度问题,根据提示标签,题解应该涉及到哈希表的应用,严格控制每个字符的出现下标,以及更新子串位置同时对比当前最长子串的位置。

    算法:

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            if(s.empty())
    			return 0;
    
    		int hash_tab[256]; //保存当前字符上一次出现的下标
    		memset(hash_tab , -1 , sizeof(hash_tab)); //hash_tab中初始化所有值为-1
    		int max_len = 0, pos = -1;//max_len即是最长子串长度 , pos为当前子串的开始位置
    
    		for(int i=0 ; i<s.length() ; i++)
    		{
    			//每个字符的元位置初始化为-1 ,当当前字符是重复字符时,改变子串的开始位置
    			if(hash_tab[s[i]] > pos)
    			{
    				pos = hash_tab[s[i]];
    			}//if
    			
    			if(i-pos > max_len)
    			{
    				max_len = i-pos;
    			}//if
    
    			//更改首次出现字符的位置
    			hash_tab[s[i]] = i;
    		}//for
    		return max_len;
        }
    };

    LeetCode03 AC代码下载

  • 相关阅读:
    c++ 学习笔记
    python 2048游戏控制器
    c++ 动态内存
    c++ 拷贝构造函数、拷贝运算符、析构函数
    c++ struct enum union加typedef与不加typedef
    c++ 动态内存2
    c++ 指针数组与指向数组的指针
    c++ TextQuery程序
    c++ virtual
    c++ 动态内存 动态数组
  • 原文地址:https://www.cnblogs.com/shine-yr/p/5214955.html
Copyright © 2011-2022 走看看