leetcode03-Longest Substring Without Repeating Characters之Java版本

我的leetcode之旅,该篇章主要完成使用Java实现算法。这是第三篇Longest Substring Without Repeating Characters
全部代码下载:Github链接:github链接,点击惊喜;写文章不易,欢迎大家采我的文章,以及给出有用的评论,当然大家也可以关注一下我的github;多谢;

1.题目简介:

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

2.我的思路:

1.使用一个字符数组记录字符是否重复
2.将没个子串的起点定义为j,终点定义为i
3.i递增当字符已经在字符数组中出现,判断max是否大于i-j;从j开始寻找找到是哪个字符相同,同时将起点j++在字符数组中去掉丢掉的字符;
4.如果字符串中最后一个字符不是重复字符,则在循环外面进行判断是否更新max

3.我的AC代码

package com.rlovep.string;
/**
 *  Longest Substring Without Repeating Characters
 *  我的思路:
 *  1.使用一个字符数组记录字符是否重复
 *  2.将没个子串的起点定义为j,终点定义为i
 *  3.i递增当字符已经在字符数组中出现,判断max是否大于i-j;从j开始寻找找到是哪个字符相同,同时将起点j++在字符数组中去掉丢掉的字符;
 *  4.如果字符串中最后一个字符不是重复字符,则在循环外面进行判断是否更新max
 * @author peace
 *
 */
public class LongSubNrep {
      public int lengthOfLongestSubstring(String s) {
        if(s==null||s.length()<=0)return 0;
        char[] a=new char[256];        
        int j=0;
        int max=0;
        int i=0;
        boolean flag=false;
        for(;i<s.length();i++){
            char c=s.charAt(i);
            if(a[c]==1){
                if(max<(i-j))max=i-j;
                flag=false;
                for(int k=j;k<i;k++){
                    char dup=s.charAt(k);
                    if(c==dup){
                        j=k+1;
                        break;
                    }else{
                        a[dup]=0;
                    }
                }
            }else{
                a[c]=1;
                flag=true;
            }
        }
        if(flag==true&&max<(i-j))max=i-j;
          return max;  
        }
      public static void main(String[] args) {
          char[] a=new char[256];

    }
}

好的本章介绍到这里 来自伊豚wpeace(blog.wpeace.cn)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值