您的位置:首页 > 其它

Leetcode:Longest Substring Without Repeating Characters 解题报告

2014-12-27 18:41 507 查看

Longest Substring Without Repeating Characters

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.

public int lengthOfLongestSubstring(String s) {
if (s == null) {
return 0;
}

int max = 0;

// suppose there are only ASCII code.
int[] lastIndex = new int[128];
for (int i = 0; i < 128; i++) {
lastIndex[i] = -1;
}

int len = s.length();
int l = 0;
for (int r = 0; r < len; r++) {
char c = s.charAt(r);

if (lastIndex[c] >= l) {
l = lastIndex[c] + 1;
}

// replace the last index of the character c.
lastIndex[c] = r;

// replace the max value.
max = Math.max(max, r - l + 1);
}

return max;
}


View Code

GITHUB:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/string/LengthOfLongestSubstring.java

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: