You are given a string consisting only of lowercase letters. A substring of is a string and its length is equal to . Find the substring of that contains a maximum number of occurrences.
If several answers exist, then print the one with the maximum length. If there are still several answers, then print the one with the minimum index of the first occurrence.
Example:
Input: xyzxyzabcabc
Output: xyz
Approach
Java
import java.util.HashSet;public class MaximumSubstring {public static void main(String[] args) {String str = "xyzxyzabcabc";String ans = maximumSubstring(str);System.out.println(ans);}static String maximumSubstring(String str) {char s[] = str.toCharArray();int n = s.length;int[] frearray = new int[26];int maxFre = 0;for (char c : s) {frearray[c - 'a']++;maxFre = Math.max(maxFre, frearray[c - 'a']);}HashSet<Character> set = new HashSet<>();for (int i = 0; i < 26; i++) {if (maxFre == frearray[i]) {set.add((char) (i + 'a'));}}String ans = s[0] + "";for (int i = 0; i < n; i++) {if (set.contains(s[i])) {int j = i;while (j + 1 < n && s[i] != s[j + 1] && set.contains(s[j + 1])) {j++;}ans = str.substring(i, j + 1);break;}}return ans;}}
No comments:
Post a Comment