Longest Substring Without Repeating Characters

 1 import java.util.Scanner;
 2 
 3 /**
 4  * Created by qmq
 5  * Given a string, find the length of the longest substring without repeating characters.
 6  * Example 1:
 7  * Input: "abcabcbb"
 8  * Output: 3
 9  * Explanation: The answer is "abc", with the length of 3.
10  *
11  * @ 18-10-12
12  **/
13 class Solution7 {
14     public int longestSubstring(String s) {
15         if (s.length() < 2) {
16             return s.length();
17         }
18         int max = -1, start = 0;
19         for (int i = 1; i < s.length(); i++) {
20             if (i < s.length()) {
21                 int index = s.substring(start, i).indexOf(s.charAt(i));
22                 if (index != -1) {
23                     max = Math.max(max, i - start);
24                     start += (index + 1);
25                 } else {
26                     max = Math.max(max, i - start);
27                 }
28             }
29         }
30         return max != -1 ? max : s.length();
31     }
32 }
33 
34 public class LongestSubstring {
35     public static void main(String[] args) {
36         Solution7 sol = new Solution7();
37         Scanner scanner = new Scanner(System.in);
38         String str = scanner.nextLine();
39         System.out.println(sol.longestSubstring(str));
40     }
41 }
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 // Given a string, find the length of the longest substring without repeating characters.
 5 // Example 1 :
 6 // Input : "abcabcbb" Output : 3 Explanation : The answer is "abc",
 7 // with the length of 3.
 8 // the first thought is to round the first situation charactor
 9 
10 // new hashmap
11 // hashmap.put(x)
12 // cnt(x)
13 // if(x>1)
14 // cnt the number[xi]
15 // new hashmap
16 // continue
17 // until find
18 // return the number[xi].max
19 
20 class Solution
21 {
22   public:
23     int LongestSubstring(char *s)
24     {
25         int len = 0;
26         char *end = s, *temp;
27         char *addressTable[128] = {NULL};
28         while (*end) //非空地址
29         {
30             temp = addressTable[*end]; //哈希表
31             addressTable[*end] = end;  //哈希表end位置初始化
32             if (temp >= s)             //当前子域大于历史域,则进行域长度更新
33             {
34                 len = end - s > len ? end - s : len;
35                 s = temp + 1;
36             }
37             end++;
38         }
39         len = end - s > len ? end - s : len; //排除最后一次迭代影响
40         return len;
41     }
42 };
43 int main()
44 {
45     char *str;
46     cin >> str;
47     Solution sol;
48     cout << sol.LongestSubstring(str) << endl;
49     return 0;
50 }
原文地址:https://www.cnblogs.com/sigmod3/p/9777064.html