标签:
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.
初步解决方法:
思路:把所有连续的子串找出来,再判断各个子串是否有重复元素
原字符串长度为n的话,所有子串的个数就是c(n,2) = n+n-1+...+1;
public class Solution { public int lengthOfLongestSubstring(String s) { int length = s.length(); boolean reflag = false; int max = 0; List<String> lists = new ArrayList<String> (); for(int i=0; i<length; i++) { for(int j=i+1; j<length; j++) { lists.add(s.substring(i,j+1)); } } for(String ssub : lists) { reflag = false; for(int i=0; i<ssub.length(); i++){ char c = ssub.charAt(i); if(ssub.indexOf(c,i+1)!=-1){ reflag = true; break; } } if(!reflag){ int sublen = ssub.length(); if(sublen > max) { max = sublen; } } } return max; } }
public static void main(String[] args) { String s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!\"#$%&"; boolean reflag = false; int max = 1; List<String> lists= new ArrayList<String>(); int length = s.length(); for(int i=0; i<length; i++) { for(int j=i+1; j<length; j++) { lists.add(s.substring(i, j+1)); } } for(String subS:lists){ reflag = false; for(int i=0; i<subS.length(); i++){ char c = subS.charAt(i); if(subS.indexOf(c, i+1)!=-1){ reflag = true; break; } } if(!reflag){ int space = subS.length(); if(space > max){ max = space; } } } System.out.println(max); System.out.println(lists.size()); System.out.println(lists.toString()); }
这种方法并不能通过leetcode的测试,但是逻辑上确实是正确的,对于特别长的字符串,会提示超时错误。
改进方法:
边查找子串边判断子串是否重复。
Longest Substring Without Repeating Characters2015年6月9日
标签:
原文地址:http://www.cnblogs.com/hixin/p/4563725.html