欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > > 文章正文

Leetcode 3 Longest Substring Without Repeating Characters,leetcoderepeating

来源: javaer 分享于  点击 38037 次 点评:158

Leetcode 3 Longest Substring Without Repeating Characters,leetcoderepeating


Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1.

Solution1

  • 最简单的方法莫过于暴力搜索了。从字符串中的第一个字符开始,往后搜索,直到找到一个字符与已搜索过的字符相同,然后再把第一个指针往后挪一个位置。重复该过程。代码实现如下:
import java.util.HashSet;
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        HashSet<Character> temp = new HashSet<Character>();
        int result = 0;
        for(int i=0,j=0;i<=j&&j<s.length();){
            char c = s.charAt(j);
            if(!temp.contains(c)){
                if(j==s.length()-1) result = Math.max(result,j-i+1);//这里是防止在末尾的时候程序直接跳出了而没有处理
                temp.add(c);
                j++;
            }else{
                result = Math.max(result,j-i);
                if(j==s.length()-1) break;
                temp.remove(s.charAt(i++));//这里是将第一个指针往后挪一个
            }
        }
        return result;
    }
}

这种方法的时间复杂度为O(n2),空间复杂度为O(n),其实这样已经很不划算了。

Solution2

  • 解法一的时间主要耗在每次有重复字符的时候,都必须将两个字符中间的字符再去遍历一次,这样便浪费了很多时间。另一种方法是只遍历一次字符串,每次都记录字符的位置,如果有重复的字符则更新该字符的位置,另外也更新计算子串长度的起始点。时间复杂度为O(n),空间复杂度也为O(n).代码如下:
import java.util.HashMap;
public class Solution {
    public int lengthOfLongestSubstring(String s) {
        HashMap<Character,Integer> temp = new HashMap<Character,Integer>();
        int result = 0;
        for(int i=0,start=0;i<s.length();i++){
            char c = s.charAt(i);
            if(temp.containsKey(c)) start = Math.max(start,temp.get(c)+1);//这里是要取二者之间的最大值。例如"abba"的时候
            result = Math.max(result,i-start+1);
            temp.put(c,i);
        }
        return result;
    }
}

相关文章

    暂无相关文章

用户点评