LeetCode笔记-A3-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.

MySolution:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        if (s.length()==0) {
            return 0;
        }
        else if (s.length()==1) {
            return 1;
        }
        else{
            int max=0;
            for (int i = 0; i < s.length(); ++i) {
                int len = LongestWithAlpha(s.substr(i,s.length()));
                if (len>max) {
                    max=len;
                }
            }
            return max;
        }

    }
    //check if the string s contains duplicate character
    int LongestWithAlpha(string s){
        int length=1;
        for (int i = 1; i < s.length(); ++i) {
            if (!isInStr(s.substr(0,i),s[i])) {
                length++;
            }else break;
        }
        return length;

    }
    bool isInStr(string s,char a){
        string::size_type idx = s.find( a );

        if ( idx != string::npos )
        {
            return true;
        }

        return false;
    }
};

总结:非常暴力的写法,速度果然也是最慢的一档QAQ
思路很简单,从第一个字母开始找最长的无重复字母的子串,一旦发生重复,就记录这个长度,然后从第二个字母开始重复上述过程。如果标准库里的find复杂度是O(n)的话,整个过程的时间复杂度是O(n^3)。写完之后就发现其实不需要从第二个字母开始,从被发现重复的字母之后的一个字母开始就可以了,比如abcdefcg,发现了重复的”c”,这时候从d开始重复上述步骤就好了,复杂度可以降到O(n^2)。不过写的时候,正在做饭,而且代码写得有点死,就懒得改了QAQ。
官方给出的解法是用hashmap让查找复杂度变成O(1),然后根据上面的思路只扫描了一遍字符串,有一点点tricky:

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int n = s.length(), ans = 0;
        Map<Character, Integer> map = new HashMap<>(); // current index of character
        // try to extend the range [i, j]
        for (int j = 0, i = 0; j < n; j++) {
            if (map.containsKey(s.charAt(j))) {
                i = Math.max(map.get(s.charAt(j)), i);
            }
            ans = Math.max(ans, j - i + 1);
            map.put(s.charAt(j), j + 1);
        }
        return ans;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值