【LeetCode题目记录-3】字符串中最长的没有重复字符的子串

来源:互联网 发布:淘宝开店实名认证照片 编辑:程序博客网 时间:2024/05/04 07:03

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.

【分析-非原创】参考:https://oj.leetcode.com/discuss/10747/my-accepted-solution-in-java

 

/* 最长的没有重复元素的子串,在结果串里面查找当前的字符串,如果不在,添加到结果串,继续;如果有,找到它在结果串中的位置,并添加当前的字符到结果串;用到字符串查找字符下标的系统函数.indexOf() */

    public static int lengthOfLongestSubString2(String s) {

        if (s.length() == 0)

            return 0;

        if (s.length() == 1)

            return 1;

        int length = 0;

        String part = "" + s.charAt(0);

        for (int i = 1; i < s.length(); i++) {

            if (part.indexOf(s.charAt(i)) == -1) {

                part = part + s.charAt(i);

            } else {

                int index = part.indexOf(s.charAt(i));

                if (part.length() > length) {

                    length = part.length();

                }

                part = part.substring(index + 1);

                i--;

            }

        }

        return part.length() > length ? part.length() : length;

    }

0 0
原创粉丝点击