Write a program to find the highest length of substring without repeating characters from given string using Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | package com.string.manupulation; import java.util.ArrayList; import java.util.HashSet; import java.util.List; public class Findsubstringlength { /* Program to find the highest length of substring without repeating characters from given string*/ public static void main(String[] args) { String str = "bbbbcdabddabclmnaabcde"; //String str = "ohvhjdml"; List<Character> substr = new ArrayList<Character>(); int ans = 0; for(int i = 0; i < str.length(); i++) { int end = i; if(substr.contains(str.charAt(end))) { if(substr.size() > ans) { ans = substr.size(); } int j = 0; while(j < substr.size()) { if(substr.get(j) == str.charAt(end)) { substr.remove(j); substr.add(str.charAt(end)); break; } else { substr.remove(j); j--; } j++; } } else { substr.add(str.charAt(end)); } } if(substr.size() > ans) { ans = substr.size(); } System.out.println("The highest length of substring without " + "repeating characters from given string: ("+str+") is "+ans); } } |
Program Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "pwwkew" Output: 3 Explanation: 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.
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.