自学内容网 自学内容网

无重复字符的最长子串(leetcode)

题目来源:https://leetcode.cn/problems/longest-substring-without-repeating-characters/description/

题意

如题,给定一个字符串s,请你找出其中不含有重复字符的最长子串的长度

思路

考点:哈希表+滑动窗口
如果我们用两重循环去遍历字符串,显然会超时,因此我们可以考虑用滑动窗口的思想做这道题,先定义两个指针l和r以及unordered_set(哈希表)用于存储出现过的字符,遍历字符串,若该字符未出现过,则r指针右移,当前字符进入哈希表,若出现过则比较l到r的距离(即r-l),然后在哈希表里将窗口的头元素删去,让l指针右移,最后输出最大的距离

编程

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
      int ans=0;
      unordered_set<char> st;
      int r=0,l=0;
      int n=s.size();
      while(r<n){
      while(r<n && st.count(s[r])==0){
      st.insert(s[r]);
      r++;
  }
  ans=max(ans,r-l);
  st.erase(s[l]);
  l++;
  }
  return ans;
    }
};

原文地址:https://blog.csdn.net/wh233z/article/details/140523650

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!