溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Longest Substring Without Repeating Characters

發布時間:2020-08-09 07:29:31 來源:ITPUB博客 閱讀:208 作者:壹頁書 欄目:編程語言

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. public class T {  
  2.     public static void main(String[] args) {  
  3.         String s1 = "pwwkew";  
  4.         String s2 = "abcabcbb";  
  5.         String s3 = "dvdf";  
  6.         String s4 = "bbbb";  
  7.         System.out.println(lengthOfLongestSubstring(s1));  
  8.   
  9.     }  
  10.   
  11.     public static int lengthOfLongestSubstring(String s) {  
  12.         int maxlength = 0;  
  13.         int leftIndex = 0;  
  14.         int rightIndex = 0;  
  15.         while (rightIndex < s.length()) {  
  16.             char target = s.charAt(rightIndex);  
  17.             int mark = -1;  
  18.             for (int i = leftIndex; i < rightIndex; i++) {  
  19.                 if (s.charAt(i) == target) {  
  20.                     mark = i + 1;  
  21.                     break;  
  22.                 }  
  23.             }  
  24.   
  25.             if (mark != -1) {  
  26.                 if ((rightIndex - leftIndex) > maxlength) {  
  27.                     maxlength = (rightIndex - leftIndex);  
  28.                 }  
  29.                 leftIndex = mark;  
  30.                 rightIndex = mark;  
  31.   
  32.             } else {  
  33.                 rightIndex++;  
  34.             }  
  35.         }  
  36.         if ((rightIndex - leftIndex) > maxlength) {  
  37.             maxlength = (rightIndex - leftIndex);  
  38.         }  
  39.         return maxlength;  
  40.     }  
  41. }  



另附網上的答案一則.
http://www.cnblogs.com/grandyang/p/4480780.html

  1. public class Solution {  
  2.     public int lengthOfLongestSubstring(String s) {  
  3.         int[] m = new int[256];  
  4.         Arrays.fill(m, -1);  
  5.         int res = 0, left = -1;  
  6.         for (int i = 0; i < s.length(); ++i) {  
  7.             left = Math.max(left, m[s.charAt(i)]);  
  8.             m[s.charAt(i)] = i;  
  9.             res = Math.max(res, i - left);  
  10.         }  
  11.         return res;  
  12.     }  

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女