您的位置:首页 > 编程语言 > Java开发

leetcode03-Longest Substring Without Repeating Characters之Java版本

2016-05-25 18:09 369 查看
我的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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息