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.

    Examples:

    Given "abcabcbb", the answer is "abc", which the length is 3.

    Given "bbbbb", the answer is "b", with the length of 1.

    Given "pwwkew", 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.


    我的基本思路:

    max记录到目前为止数到的子字符串中最长的长度;

    current记录当前数到的子字符串的长度;

    startPos记录当前数到的子字符串的起始位置;

    sucket[a]表示字符a是否已存在与子字符串中(因为总共只有256中可能的字符,因此直接存在一个长为256的数组中即可,1表示已存在,0表示不存在);

    每操作一次就更新一次max

    如果字符串s为空,直接返回0;

    首先将s第一个字符看作当前子字符串,startPos = 0, current = 1;

    用 i 表示当前子字符串的结束坐标,从 1 移到 s 的最后一个字符;

    在移动过程中,如果 i 处字符已出现,将startPos 移到子字符串中和 i 处字符相同的字符位置下一位并更新current;

    循环结束后max即为所求。


     

    我的代码如下:

    class Solution {
    public:
        int lengthOfLongestSubstring(string s) {
            if (s.length() == 0) return 0;
            // bucket[a] means whether the character a is already in the substring
            // 1 means yes, 0 means not
            int* bucket = new int[256];
            for (int i = 0; i < 256; i++) bucket[i] = 0;
            bucket[s[0]] = 1;
            //max stores the max length of all substrings
            //current stores the length of current substring
            //startPos stores the start position of current substring
            int max = 1, current = 1, startPos = 0;
            for (int i = 1; i < s.length(); i++) {
                // refresh the value of max
                if (current > max) max = current;
                // if the character s[i] is already in the substring
                if (bucket[s[i]]) {
                    for (int j = startPos; j < i; j++) {
                        startPos++;
                        if (s[j] == s[i]) break;
                        bucket[s[j]] = 0;
                        current--;
                    }
                } else {
                    bucket[s[i]] = 1;
                    current++;
                }
            }
            if (current > max) max = current;
            return max;
        }
    };
  • 相关阅读:
    关于js中"window.location.href"、"location.href"、"parent.location.href"、"top.location.href"的用法
    对于json数据的应用01
    关于session应用(1)session过期时间设置
    关于session应用(2)JAVA中怎么使用session
    Jquery常用技巧(3)
    0101对称二叉树 Marathon
    0112路径之和 & 0113所有路径之和 Marathon
    0106105从中序与后序遍历序列中构造二叉树 Marathon
    0110平衡二叉树 Marathon
    0513找树左下角的值 Marathon
  • 原文地址:https://www.cnblogs.com/zmj97/p/7526841.html
Copyright © 2011-2022 走看看