Saturday, April 16, 2022

Leet Code 3. Longest Substring Without Repeating Characters

https://leetcode.com/problems/longest-substring-without-repeating-characters/

Example 1:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.







package pep.Day63;

import java.util.HashMap;

public class LeetCode_3_Longest_Substring_Without_Repeating_Characters {
public static void main(String[] args) {
System.out.println(lengthOfLongestSubstring("tmmzuxt"));
}

public static int lengthOfLongestSubstring(String s) {
char[] arr = s.toCharArray();
HashMap<Character, Integer> map = new HashMap<>();
int length = 0;
int left = 0;
for (int right = 0; right < arr.length; right++) {
char ch = arr[right];
if (map.containsKey(ch))
left = Math.max(left, map.get(ch) + 1);
map.put(ch, right);
length = Math.max(length, right - left + 1);

}

return length;
}

public static int lengthOfLongestSubstring1(String s) {
HashMap<Character, Integer> map = new HashMap<>();
int length = 0;
int left = 0, right = 0;

while (right < s.length()) {

if (map.containsKey(s.charAt(right)))
left = Math.max(left, map.get(s.charAt(right)) + 1);
map.put(s.charAt(right), right);
length = Math.max(length, right - left + 1);
right++;
}
return length;
}

}


No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...