无重复字符的最长子串-java

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/idealcitier/article/details/82355179

无重复字符的最长子串

问题

给定一个字符串,找出不含有重复字符的最长子串的长度。

详细的实例

实例:

输入: “abcabcbb”
输出: 3
解释: 无重复字符的最长子串是 “abc”,其长度为 3。

实例:

输入: “bbbbb”
输出: 1
解释: 无重复字符的最长子串是 “b”,其长度为 1。

实例:

输入: “pwwkew”
输出: 3
解释: 无重复字符的最长子串是 “wke”,其长度为 3。
请注意,答案必须是一个子串,”pwke” 是一个子序列 而不是子串。

思路

解决的思路:
遍历出所有的子串,查看子串中是否有重复的字符,如果有相同的字符就不是本题所需要.

遍历所有子串的方法在文章求字符串的所有子串中有讲述.
下面说一下判断一个子串中是否有重复的字符的思路:

用到的知识点

主要使用的java中set的特性,Set 接口实例存储的是无序的,不重复的数据.具体的实现类有HashSet和TreeSet.
set集合中contains()方法的用法:

public boolean contains(Object o)
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).
Specified by:
contains in interface Collection
Specified by:
contains in interface Set
Overrides:
contains in class AbstractCollection
Parameters:
o - element whose presence in this set is to be testedReturns:
true if this set contains the specified element

set集合添加元素使用add()方法.

思路详解

求出字符串所有的子串,然后对子串一一进行判定,判定子串是不是含有相同的字符,如果含有相同的字符就返回一个false,没有相同的字符就返回true.然后找出最长的长度的字符,这样就解决了问题.

实现算法

下面是具体实现算法

import java.util.*;

class GetSubstring{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        String str = sc.next();

        //String str = "pwwkew";
        //System.out.println(str);
        int len = 0;
        //System.out.println("-------------");
        for(int i = 0; i < str.length(); i++){
            for (int j = i+1; j<=str.length(); j++){
        //      System.out.println(str.substring(i,j));
                if(unique(str.substring(i,j))){
                    if(str.substring(i,j).length() > len )

                        len = str.substring(i,j).length();
                }
            }
        }
        System.out.println(len);

    }

    public static boolean unique(String str){
        Set<Character> set= new HashSet<>();

        for(int i = 0; i<str.length();i++){
            char ch = str.charAt(i);

            if( set.contains(ch) ){
                return false;
            }
            set.add(ch);

        }
        return true;
    }

}

引用

[1] https://leetcode-cn.com/articles/longest-substring-without-repeating-characters/
[2] https://blog.csdn.net/idealcitier/article/details/82350418

猜你喜欢

转载自blog.csdn.net/idealcitier/article/details/82355179