您的位置:首页 > 其它

3.Longest Substring Without Repeating Characters(7.66%)

2016-01-06 20:10 417 查看
题目: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.

个人理解:求最长的没有重复的字符串的长度。刚开始的时候贪图便利,用Java自带的字符串方法进行操作,结果超时了:

public class Solution {
public int lengthOfLongestSubstring(String s) {
int inputLength = s.length();

int longestLength = 0;
for (int i = 0; i < inputLength; i++) {
String tempString = String.valueOf(s.charAt(i));

for (int j = i + 1; j < inputLength; j++) {
String character = String.valueOf(s.charAt(j));
if (tempString.contains(character)) {
break;
} else {
tempString = tempString.concat(character);
}
}
longestLength = longestLength > tempString.length() ? longestLength : tempString.length();
}

return longestLength;
}
}


后来百度了一下,才想起Java字符数组:

public class Solution {
public int lengthOfLongestSubstring(String s) {
int inputLength = s.length();
char[] chars = s.toCharArray();

int longestLength = 0;
for (int i = 0; i < inputLength; i++) {
int oneLength = 0;
for (int j = i + 1; j < inputLength; j++) {

boolean isLegal = true;
for (int k = i; k < j; k++) {
if (chars[k] == chars[j]) {
isLegal = false;
break;
}
}

if (isLegal) {
oneLength++;
} else {
break;
}
}

oneLength++;
longestLength = longestLength > oneLength ? longestLength : oneLength;

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