Longest Substring Without Repeating Characters leetcode

来源:互联网 发布:微喜帖制作软件 编辑:程序博客网 时间:2024/06/05 15:11

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.

package leetcode;import java.util.Iterator;import java.util.LinkedHashMap;import java.util.Map;import java.util.Map.Entry;public class Solution {    public int lengthOfLongestSubstring(String s) {        int maxlength=0;        int curlength=0;        Map<Character,Integer> map=new LinkedHashMap<Character,Integer>();        for(int i=0;i<s.length();i++){        if(map.containsKey(s.charAt(i))){        curlength=i-map.get(s.charAt(i));        Iterator<Entry<Character, Integer>> it = map.entrySet().iterator();                  while(it.hasNext()){                      Entry<Character, Integer> entry=it.next();                     it.remove();                    if(entry.getKey()==s.charAt(i)){                     break;                    }                }         map.put(s.charAt(i), i);        maxlength=maxlength>curlength?maxlength:curlength;        }else{        map.put(s.charAt(i), i);        curlength++;                maxlength=maxlength>curlength?maxlength:curlength;        }        }        return maxlength;    }    public static void main(String[]args){    Solution s=new Solution();    System.out.print(s.lengthOfLongestSubstring("cdd"));    }}


0 0
原创粉丝点击