zoukankan      html  css  js  c++  java
  • LeetCode之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.

    【解决思路】

    方法可能比较笨,但是可用成功解决此问题,通过判断当前已存储的字符串中,是否已经有新的字符串了。如果存在则将其删除至oldchar位置,来保证当前字符串中没有重复字符串。

    【代码实现】

    private int length = 0;
        private StringBuilder sb = new StringBuilder();
        public int lengthOfLongestSubstring(String s)
        {
            int count = 0;
            for(char c : s.toCharArray())
            {
                if(sb.toString().contains(String.valueOf(c)))
                {
                    //查找当前已经存在相同字符的位置,并将其之前的删除,仅保留后续字符,避免字符重复。
                    int frist_index = sb.toString().indexOf(c) + 1;
                    String str = sb.toString().substring(frist_index);
                    sb =  new StringBuilder(str);
                    sb.append(c);
                    //由于已经更新了字符串信息,所以长度信息同步更新。
                    count = count - frist_index + 1;
                    continue;
                }
                sb.append(c);
                count ++;
                //保证当前length中存储的是最长字符串长度
                length = Math.max(length, count);
            }

    return Math.max(length, count); }

    【后续】

    查看了leetcode上的相关解决思路,有个方法比较好,通过一个set来存储,避免了重复创建对象,这个方法还是比较好的,在此也贴下代码,以便后续学习用。

        public int lengthOfLongestSubstring2(String s) {
            int n = s.length();
            Set<Character> set = new HashSet<>();
            int ans = 0, i = 0, j = 0;
            while (i < n && j < n) {
                // try to extend the range [i, j]
                if (!set.contains(s.charAt(j))){
                    set.add(s.charAt(j++));
                    ans = Math.max(ans, j - i);
                }
                else {
                    set.remove(s.charAt(i++));
                }
            }
            return ans;
        }
  • 相关阅读:
    tomcat调试模式出问题的解决方法
    文本输入 的 onfucus 和 onblur
    how to choose one of compenent and control
    C# Captcha 测试 firefox 和 IE
    谈谈对GridView控件DataKeyName属性的一点认识
    Response.Redirect和Server.Transfer的区别
    select 基本常用语法
    top、postop、scrolltop、scrollHeight、offsetHeight
    onchange 和 onpropertychange区别
    try catch 和if else 语句区别细说
  • 原文地址:https://www.cnblogs.com/woniu4/p/8422997.html
Copyright © 2011-2022 走看看