Longest Substring Without Repeating Characters

来源:互联网 发布:阿里云创建自定义镜像 编辑:程序博客网 时间:2024/06/07 08:37


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.

这道题目最主要的事情 就是查找重复,这也是用hashset 实现的一个原因。同样,对于这道题目,也可以用string 的 indexOf() 方法完成去重。

除了去重,则需要考虑 left boundary 和 right boundary的判断问题了。


public class Solution {    public int lengthOfLongestSubstring(String s) {        if (s == null || s.length() == 0) {            return 0;        }               int right = 0;         int res = 0;        String sub = "";        while(right < s.length()) {            while (right < s.length() && sub.indexOf(s.charAt(right)) == - 1) {                sub += s.charAt(right);                right++;            }            if (right < s.length()) {                res = Math.max(res, sub.length());                sub = sub.substring(sub.indexOf(s.charAt(right)) +1) + s.charAt(right);                 right ++;            }        }       return res = Math.max(res, sub.length());            }}


public class Solution {    public int lengthOfLongestSubstring(String s) {        if (s == null || s.length() == 0) {            return 0;        }                HashSet<Character> set = new HashSet<Character>();                int leftBound = 0, max = 0;        for (int i = 0; i < s.length(); i++) {            if (set.contains(s.charAt(i))) {                while (leftBound < i && s.charAt(leftBound) != s.charAt(i)) {                    set.remove(s.charAt(leftBound));                    leftBound ++;                }                leftBound ++;            } else {                set.add(s.charAt(i));                max = Math.max(max, i - leftBound + 1);            }        }                return max;    }}


0 0
原创粉丝点击