leetcode Longest Substring Without Repeating Characters

来源:互联网 发布:西西河陈经 知乎 编辑:程序博客网 时间:2024/06/09 17:41

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.

下面是我的程序(说来惭愧,此处参考了http://www.cnblogs.com/luxiaoxun/archive/2012/10/02/2710471.html)

package com.my.own;public class Solution5 {public int lengthOfLongestSubstring(String s) {if((s==null) || (s.equals(""))){return 0;}if(s.length() == 1){return 1;}int [] next = new int[s.length()];int[] first = new int[s.length() +1];first[s.length()]  =  s.length();for(int i=s.length() -1; i>=0; i--){next[i] = s.indexOf(s.charAt(i), i+1)==-1 ? s.length() : s.indexOf(s.charAt(i), i+1);if(next[i] <first[i+1]){first[i] = next[i];}else{first[i] = first[i+1];}}int maxLen = 0;for(int i=0; i<s.length(); i++){if(maxLen <(first[i] -i)){maxLen = first[i] -i;}}return maxLen;}public static void main(String[] args) {Solution5 s5 = new Solution5();String s= "bbbbb";System.out.println(s5.lengthOfLongestSubstring(s));}}



0 0
原创粉丝点击