您的位置:首页 > 其它

LeetCode Longest Substring Without Repeating Characters

2015-05-27 12:45 344 查看
Description

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.

Solution:

First we use a loop to get an array, arr. arr[i] represents the leftmost character index on the right of character i. Then we can operate on the array arr to get the final answer.

For each character i, we loop to its arr[i]( upper = arr[i] ). During this process, we find whether there exists character j satisfies that arr[j] < upper, if so then we just updates upper = arr[j]. After this loop beginning from i, we can tell that max
= max{ max. arr[j] - i}.

import java.util.Arrays;

public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.equals(""))
return 0;
int max = 1;
int l = s.length();
int arr[] = new int[l];
Arrays.fill(arr, l);

loop: for (int i = 0; i < l; i++)
for (int j = i + 1; j < l; j++)
if (s.charAt(i) == s.charAt(j)) {
arr[i] = j;
continue loop;
}

for (int i = 0; i < l; i++)
System.out.print(arr[i] + " ");
System.out.println();

loop: for (int i = 0; i < l; i++) {
int temp = arr[i] - i;
int upper = arr[i];
for (int j = i + 1; j <= upper && j < l; j++)
if (arr[j] < upper) {
temp = arr[j] - i;
upper = arr[j];
}
max = Math.max(max, temp);
}

return max;
}

public static void main(String[] args) {
String s = "cdd";
Solution so = new Solution();
System.out.println(so.lengthOfLongestSubstring(s));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: