leetcode 3. Longest Substring Without Repeating Characters

来源:互联网 发布:搜索引擎算法定义 编辑:程序博客网 时间:2024/06/11 08:17
//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.public class Solution {public static void main(String[] args) {lengthOfLongestSubstring("abba");}public static int lengthOfLongestSubstring(String s) {if(s == null) return 0;boolean flag[] = new boolean[256];//判断字符是否被访问过的bool数组,[]中的index为字符char arr[] = s.toCharArray();int i = 0;//遍历字符串int result = 0;//结果int start = 0;//每一次比较字符串有无重复的起点while(i<arr.length){char current = arr[i];if(flag[current] == true){//判断当前字符是否之前是否出现过result = Math.max(result, i-start);//若出现过则取到二者之间的字符串个数+1for(int k = start;k<i;k++){//将下轮比较的起点确定在之前出现过的相同字符的下一个位置,并将之前访问过并且相同字符中没有的字符flag重置if(arr[k] == current){//如果出现“abcb”这种情况,则start = 2,flag[a] = falsestart = k+1;break;}else{flag[k] = false;}}}else{flag[current] = true;//若之前没有出现过与该字符相同的,则将该字符flag置为true}i++;}result = Math.max(arr.length-start, result);//字符串末尾到最近一轮比较起点之间的字符个数与之前得到的结果最大值即为最终结果System.out.println(result);return result;} }

0 0
原创粉丝点击