Longest Substring Without Repeating Characters

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.需要两个指针第一个从头开始for循环一直到string结束,第二个用于找最长substring, 

2.需要一个数组 用途是做一个映射 利用ascii码表中char的数字映射在数组中的位置存放0或者1两个数字表示是否已经存在。

3.需要一个整数值存放最长字符串的长度,也就是最终答案。

class Solution {

    public int lengthOfLongestSubstring(String s) {

        int i = 0, j = 0, ans = 0;

        int[] myMap = new int[128];

        for(i = 0; i < s.length(); i++){

            while(j < s.length() && myMap[s.charAt(j)] == 0){

                myMap[s.charAt(j)] = 1;

                ans = Math.max(ans, j-i+1);

                j++;

            }

            myMap[s.charAt(i)] = 0;

        }

        return ans;

    }

}

你可能感兴趣的:(Longest Substring Without Repeating Characters)