Question:
Given a string, find the length of the longest substring without repeating characters.
Examples:
Given "abcabcbb", the answer is "abc", which the length is 3.
Given "bbbbb", the answer is "b", with the length of 1.
Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
题目意思是求解字符串中连续的不重复的长度
思路:
1、首先需要一个计数器,去记录最大不重复连续字符串的长度。
2、需要一个集合(List,Set都行),去存放不重复的字符串。
3、对字符串进行判断,若为空,则直接返回0。不为空,应首先向集合中添加字符串的第一个元素,计数器count++;
4、应需要一个判别标志flag,去判断下一个字符是否为重复,重复为false
5、需要两个嵌套循环,第一层是遍历字符串,第二层去遍历集合,若集合中有元素与字符串当前字符相同,则跳出循环。并且flag为false。
6、第二层循环遍历完后,判断【j】的索引是否与集合大小相等。(相等说明当前字符没有与集合中任何元素相同)。相等后,还要进行判断当前索引是否和计数器的值相等(count应该记录的是最大不重复的长度),若相等,count++
7、若有重复元素,flag为false,则应该删除第一个至索引处的集合元素。flag=true
8、最后添加当前的字符到集合(无论如何都要添加),进入下一次循环
9、两层循环遍历完后,返回count
核心代码:
public class Solution {
public int lengthOfLongestSubstring(String s) {
int count=0;
boolean flag=true;
List<Character>list=new ArrayList<>();
if(!s.equals("")){
list.add(s.charAt(0));
count++;
}
for(int i=1;i<s.length();i++){
int j=0;
for(;j<list.size();j++){
if(list.get(j).equals(s.charAt(i))){
flag=false;
break;
}
}
if(j==list.size()){
if(j==count)
count++;
}
if(flag==false){
for(int k=0;k<=j;k++)
list.remove(0);
flag=true;
}
list.add(s.charAt(i));
}
return count;
}
本文介绍了一种求解字符串中最长无重复字符子串长度的算法实现,通过使用计数器和集合来记录和判断字符是否重复,适用于面试和技术交流。
675

被折叠的 条评论
为什么被折叠?



