Leetcode旅途三

来源:互联网 发布:it 网络管理系统 价格 编辑:程序博客网 时间:2024/06/06 02:55

No.3: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.

 

解题思路:

这道题求的是最长不重复的子字符串。

第一个能想到的方法自然是两层嵌套循环的,时间复杂度自然是O(n)。

第二个方法是运用贪心算法,寻找两个相同字符字符串之间的最长子串。因为最长不重复的子字符串必然是存在于两个重复的字符之间。

具体实现代码如下:

 public int lengthOfLongestSubstring(String s) {
        int[] count = new int [255];
        int max = 0, start = 0;
        for(int i= 0; i < 255; i++) count[i] = -1;
        for(int i = 0; i < s.length();i++){
            if(count[s.charAt(i)] > start){
              if(i - start >= max)
                 max = i - start;
              start = count[s.charAt(i)] + 1;
             }
             count[s.charAt(i)] = i;
        }
        if(max > s.length() - start)
           return max;
        else
          return s.length() - start;
    }

 

 

0 0
原创粉丝点击