Longest substring
Problem to find the length of the longest substring without repeating characters.
Example-1:
Input : S = "abcabcbb" Output : 3 Explain : "abc" is a longest substring without repeating characters.
Example-2:
Input : S = "aaaa" Output : 1 Explain : "a" is a longest substring without repeating characters.
Example-3:
Input : S = "dvdf" Output : 3 Explain : "vdf" is a longest substring without repeating characters.
Solution
public class Main { public static void main(String [] args) { String s = "abcabcbb"; String ans = ""; int count = 0; for (int i=0;i<s.length();i++) { ans = ans + s.charAt(i); for (int j = i+1; j<s.length(); j++) { if(ans.indexOf(s.charAt(j)) == -1) { ans = ans + s.charAt(j); } else { break; } } if(ans.length()>count) { count = ans.length(); } ans = ""; } System.out.print(count); } }
Output
3