Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Given a string, find the length of the longest substring without repeating chara

ID: 3869091 • Letter: G

Question

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.

assume there are no spaces in the input and only alphanumeric characters are allowed.

Also, if you use a char pointer for the input, you don't need to know the size of the input (I assume).

c++

comment each line of code, show input and output(screenshot is fine.)

TYPE IT PLEASE

Explanation / Answer

public int lengthOfLongestSubstring(String s) {

        if(s==null)

            return 0;

                boolean[] flag = new boolean[256];

                int result = 0;

                int start = 0;

                char[] arr = s.toCharArray();

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

                                char current = arr[i];

                                if (flag[current]) {

                                                result = Math.max(result, i - start);

                                                // the loop update the new start point

                                                // and reset flag array

                                                // for example, abccab, when it comes to 2nd c,

                                                // it update start from 0 to 3, reset flag for a,b

                                                for (int k = start; k < i; k++) {

                                                                if (arr[k] == current) {

                                                                                start = k + 1;

                                                                                break;

                                                                }

                                                                flag[arr[k]] = false;

                                                }

                                } else {

                                                flag[current] = true;

                                }

                }

result = Math.max(arr.length - start, result);

return result;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote