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

    Given a string, find the length of the longest substring without repeating characters.

    Example 1:

    Input: "abcabcbb"
    Output: 3 
    Explanation: The answer is "abc", with the length of 3. 
    

    Example 2:

    Input: "bbbbb"
    Output: 1
    Explanation: The answer is "b", with the length of 1.
    

    Example 3:

    Input: "pwwkew"
    Output: 3
    Explanation: The answer is "wke", with the length of 3. 
                 Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
     1 class Solution {
     2 public:
     3     int lengthOfLongestSubstring(string s) {
     4         int len = 0,st=0,ed=0;
     5         set<char>q;
     6         for (int i = 0; s[i]; i++) {
     7             set<char>::iterator i1 = q.find(s[i]);
     8             if (i1 != q.end()) {
     9                 len = max(len, ed - st );
    10                 while (s[st] != s[i]) {
    11                     q.erase(q.find(s[st]));
    12                     st++;
    13                 }
    14                 q.erase(q.find(s[st]));
    15                 st++;
    16             }
    17             q.insert(s[i]);
    18             ed++;
    19         }
    20         len = max(len, ed - st );
    21         cout << len << endl;
    22         return len;
    23     }
    24 };
    View Code

    滑动窗口,看题解最优化的解法是在这个方案的基础上把遇到重复字符时一个个增加头指针位置换成直接跳到重复字符之后。

    注定失败的战争,也要拼尽全力去打赢它; 就算输,也要输得足够漂亮。
  • 相关阅读:
    B 基因改造
    A 密码锁
    Leetcode(884)-索引处的解码字符串
    Leetcode(885)- 救生艇
    Leetcode(23)-合并K个排序链表
    关于优先队列的总结II
    重载运算符问题
    Leetcode(22)-括号生成
    Leetcode(102)-二叉树的层次遍历
    Leetcode(82)-删除排序链表中的重复元素 II
  • 原文地址:https://www.cnblogs.com/yalphait/p/10255213.html
Copyright © 2011-2022 走看看