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;
        }
    };
  • 相关阅读:
    spring execution表达式用法
    spring2.0中使用Aspect方式进行AOP如何得到method对象
    mybatis if标签判断字符串相等
    Date和Timestamp区别
    正向代理与反向代理[转载]
    oracle中的对象创建及删除语句【原创】
    使用IDEA打war包并导出war包详细步骤
    Java面试题
    电脑上怎么登录几个微信(微信多开)
    批处理快速合并多分Excel文件并将指定列的数据去重复
  • 原文地址:https://www.cnblogs.com/zmj97/p/7526841.html
Copyright © 2011-2022 走看看