首页 > 其他 > 详细

Longest Substring Without Repeating Characters

时间:2016-08-22 22:57:16      阅读:238      评论:0      收藏:0      [点我收藏+]

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.

解题思路 :利用hashmap, 记录字符是否出现过,如果出现过将子序列的起始位置移动到已经存在的字符的后一个位置。

 1 public class Solution {
 2     public int lengthOfLongestSubstring(String s) {
 3         if (s == null || s.length() == 0) {
 4             return 0;
 5         }
 6         int[] map = new int[256];
 7         Arrays.fill(map, -1);
 8         int left = 0, right = 0;
 9         int result = 0;
10         for (right = 0; right < s.length(); right++) {
11             int ch = s.charAt(right);
12             while (map[ch] != -1 && left < right) {
13                 int temp = s.charAt(left);
14                 ++left;
15                 map[temp] = -1;
16             }
17             map[ch] = 1;
18             result = Math.max(result, right - left + 1);
19         }
20         return result;
21     }
22 }

 

Longest Substring Without Repeating Characters

原文:http://www.cnblogs.com/FLAGyuri/p/5797146.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!