您的位置:首页 > 其它

LeetCode_Longest Substring Without Repeating Characters

2015-11-13 23:07 260 查看
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.

解题思路:两个指针,第一个指针遍历整个字符串,第二个指针并记录子串的起始位置。代码中,遍历指针即为for循环中的i,起始位置记录指针为startIndex。遍历过程中,发现有字母已经在之前的子串中出现过,则将开始指针移动至第一次出现的位置+1。并且计算当前的length,与之前记录的length比较,取大者。

Time Limit Exceeded

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

List<String> charArr = new ArrayList<String>();

int length = 0;
int startIndex = 0;
if (s.length() == 0) {
return 0;
}

for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
String key = String.valueOf(c);
if (charArr.contains(key)) {
int tmpLength = i - startIndex;
int index = charArr.indexOf(key);
startIndex = index + 1;

length = length < tmpLength ? tmpLength : length;

for (int j = 0; j < startIndex; j++) {
charArr.add(j, "-");
}
}
charArr.add(key);
}
int tmpLength = s.length() - startIndex;
length = length < tmpLength ? tmpLength : length;
return length;
}
}

Accepted

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

Map<String, Integer> charMap = new HashMap<String, Integer>();
int length = 0;
int startIndex = 0;
if (s.length() == 0) {
return 0;
}

for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
String key = String.valueOf(c);
if (charMap.containsKey(key)) {
int tmpLength = i - startIndex; // 发现存在,则计算当前最大长度
length = length < tmpLength ? tmpLength : length; // 取最大长度
if (charMap.get(key) >= startIndex) {
startIndex = charMap.get(key) + 1; // 开始位置记录为上一次出现的位置+1
}
charMap.put(key, i);
} else {
charMap.put(key, i);
}
}

int tmpLength = s.length() - startIndex;
length = length < tmpLength ? tmpLength : length;
return length;
}
}


膜拜解法:

public int lengthOfLongestSubstring1(String s) {
int begin = 0, end = 0;
int flag[] = new int[256];
int max = 0;

while (end < s.length()) {
if (flag[s.charAt(end)] == 0) { // 未标记,说明未出现过
flag[s.charAt(end)]++; // 标记之,已经出现
end++; // 遍历下一个
max = (end - begin) > max ? (end - begin) : max;
} else {
flag[s.charAt(begin)]--; // 已经遍历到此字母,清除
begin++;
}
}
return max;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: