- import java.util.HashMap;
- import java.util.Scanner;
-
- public class MINtech {
-
- public static int lengthOfLongestSubstring(String s) {
- // Initialize a HashMap to store the last index of each character
- HashMap lastIdxMap = new HashMap<>();
- // Initialize variables to keep track of the start of the current substring and the length of the longest substring
- int start = 0;
- int maxLength = 0;
-
- // Iterate through the characters of the string
- for (int end = 0; end < s.length(); end++) {
- // If the current character is already in the substring, update the start index
- if (lastIdxMap.containsKey(s.charAt(end)) && lastIdxMap.get(s.charAt(end)) >= start) {
- start = lastIdxMap.get(s.charAt(end)) + 1;
- }
-
- // Update the last index of the current character
- lastIdxMap.put(s.charAt(end), end);
-
- // Update the length of the longest substring if needed
- maxLength = Math.max(maxLength, end - start + 1);
- }
-
- return maxLength;
- }
-
- public static void main(String[] args) {
- // Get user input for the string
- Scanner scanner = new Scanner(System.in);
- System.out.print("Enter any string :- ");
- String inputString = scanner.nextLine();
-
- // Calculate and print the length of the longest substring without repeating characters
- int result = lengthOfLongestSubstring(inputString);
- System.out.println("Length of the longest substring without repeating characters :-- " + result);
- }
- }
No comments:
Post a Comment