题解 | #最长不含重复字符的子字符串#

最长不含重复字符的子字符串

https://www.nowcoder.com/practice/48d2ff79b8564c40a50fa79f9d5fa9c7?tpId=265&rp=1&ru=%2Fexam%2Foj%2Fta&qru=%2Fexam%2Foj%2Fta&sourceUrl=%2Fexam%2Foj%2Fta%3FjudgeStatus%3D3%26page%3D1%26pageSize%3D50%26search%3D%26tpId%3D13%26type%3D265&difficulty=&judgeStatus=3&tags=&title=&gioEnter=menu

滑动窗口

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param s string字符串 
     * @return int整型
     */
    int lengthOfLongestSubstring(string s) {
      if (s.empty()) {
        return 0;
      }
      
      //  最少单个字符
      std::unordered_map<char, int> hash;
      int left = 0, right = 0;
      int res = 1;
      
      while (right < s.size()) {
        ++hash[s[right]];
        
        while (hash[s[right]] > 1) {
          if (hash.count(s[left])) {
            --hash[s[left]];
          } 
          ++left;
        }
        
        ++right;
        
        res = std::max(res, right - left);
      }
      
      return res;
    }
};
全部评论

相关推荐

评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务