zoukankan      html  css  js  c++  java
  • leetcode--Longest Substring Without Repeating Characters

    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.

    Code 1: The algorithm is simple and the running time is O(n), where n is the length of the string

    public class Solution {
        public int lengthOfLongestSubstring(String s) {
           int max = 0;
    		int length = s.length();
    		if(length > 0){
    			Map<Character, Integer> distinguish = new HashMap<Character, Integer>();
    			int startIndex = 0;
    			for(int i = 0; i < length; ++i){
    				if(distinguish.containsKey(s.charAt(i))) {
    					int temp = distinguish.get(s.charAt(i));
    				
    					for(int j = startIndex; j < temp + 1; ++j)
    						distinguish.remove(s.charAt(j));
    				
    					startIndex = temp + 1;
    				}
    				distinguish.put(s.charAt(i), i);
    				max = Math.max(max, i - startIndex + 1);
    			}
    		}
    		return max;    
        }
    }
    

      

    Code 2:

     1 public class Solution {
     2     public int lengthOfLongestSubstring(String s) {
     3         int len = 0;
     4         HashSet<Character> hset = new HashSet<Character>(); 
     5         if(s.length() > 0){
     6             StringBuffer temp = new StringBuffer();
     7             temp.append(s.charAt(0));
     8             hset.add(s.charAt(0));
     9             ++len;
    10             for(int i = 1; i < s.length(); ++i){
    11                 if(hset.contains(s.charAt(i))){
    12                     StringBuffer abf = new StringBuffer();
    13                     abf.append(s.charAt(i));                    
    14                     int index = temp.indexOf(abf.toString());
    15                     temp.delete(0, index + 1);
    16                 }
    17                 else
    18                     hset.add(s.charAt(i));                
    19                 temp.append(s.charAt(i));
    20                 if(temp.length() > len)
    21                     len = temp.length();
    22             }            
    23         }
    24         return len;
    25     }
    26 }
  • 相关阅读:
    uniapp IOS使用uni.getLocation获取不到具体城市名字
    uniapp 打开[ios/安卓]GPS定位权限
    for循环中利用计时器使用let和var
    uniapp 调起底部输入框textarea聊天页面被键盘顶起
    父子组件传布尔类型,发现有问题一直传字符串
    Kafka学习-基础知识
    剑指offer-删除链表中重复的节点
    LEACH协议原文详解
    主流机器学习框架
    算法工程师-职位描述
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3536686.html
Copyright © 2011-2022 走看看