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.
- public class T {
- public static void main(String[] args) {
- String s1 = "pwwkew";
- String s2 = "abcabcbb";
- String s3 = "dvdf";
- String s4 = "bbbb";
- System.out.println(lengthOfLongestSubstring(s1));
- }
- public static int lengthOfLongestSubstring(String s) {
- int maxlength = 0;
- int leftIndex = 0;
- int rightIndex = 0;
- while (rightIndex < s.length()) {
- char target = s.charAt(rightIndex);
- int mark = -1;
- for (int i = leftIndex; i < rightIndex; i++) {
- if (s.charAt(i) == target) {
- mark = i + 1;
- break;
- }
- }
- if (mark != -1) {
- if ((rightIndex - leftIndex) > maxlength) {
- maxlength = (rightIndex - leftIndex);
- }
- leftIndex = mark;
- rightIndex = mark;
- } else {
- rightIndex++;
- }
- }
- if ((rightIndex - leftIndex) > maxlength) {
- maxlength = (rightIndex - leftIndex);
- }
- return maxlength;
- }
- }
另附网上的答案一则.
http://www.cnblogs.com/grandyang/p/4480780.html
- public class Solution {
- public int lengthOfLongestSubstring(String s) {
- int[] m = new int[256];
- Arrays.fill(m, -1);
- int res = 0, left = -1;
- for (int i = 0; i < s.length(); ++i) {
- left = Math.max(left, m[s.charAt(i)]);
- m[s.charAt(i)] = i;
- res = Math.max(res, i - left);
- }
- return res;
- }
- }