Longest Substring Without Repeating Characters

发布时间:2020-08-09 07:29:31 作者:壹頁書
来源:ITPUB博客 阅读:158

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.     }  

推荐阅读:
  1. Java无重复字符的最长子串怎么实现
  2. leetcode中如何查看无重复字符的最长子串

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

characters repeating without

上一篇:attachMovie

下一篇:亲身经历的一次Mysql OCP考试

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》