Repetitive substrings
Check if string contains the exact same number of repetitions of every character. I.e. "aabb" - true, "aabbc" - false. Then check if removing a single character from the string can make it valid, i.e. "aabbc" - true, "aaabbbcc" - false
public boolean repnumber(String s) {
boolean result = true;
char prev = '\0';
int maxcount = 0, count = 0, mincount = s.length();
Map<Integer, Integer> frequencies = new HashMap<>();
for(int i=0; i<s.length();i++) {
char c = s.charAt(i);
if((prev!='\0' && prev != c)) {
if (frequencies.containsKey(count)) {
frequencies.put(count, frequencies.get(count) + 1);
} else {
frequencies.put(count, 1);
}
count = 0;
}
count++;
prev = c;
}
if (frequencies.containsKey(count)) {
frequencies.put(count, frequencies.get(count) + 1);
} else {
frequencies.put(count, 1);
}
if(frequencies.size() > 2) return false;
if(frequencies.size() == 1) return true;
List<Integer> list = new ArrayList<>(frequencies.keySet());
int max = Math.max(list.get(0), list.get(1));
int min = Math.min(list.get(0), list.get(1));
if(frequencies.get(max) == 1 && max-min == 1) return true;
if(frequencies.get(min) == 1 && min == 1) return true;
return false;
}
SubArray sum
In an array of non-negative intergers find a sequence of integers which sum up to the given number. I.e. [1, 2, 3], find 5 -> return [2, 3]
public int sums(int[] seq, int sum) {
int csum = 0, right = 0, left = 0;
boolean notfound = true;
while(right < seq.length && notfound) {
for(int i = right; i < seq.length; i++) {
csum +=seq[i];
if(csum == sum) {left = i; notfound=false; break;}
if(csum > sum) { csum=0; break;}
}
csum=0;
right++;
}
if(notfound) {right=1; left = -1; }
int[] res = Arrays.copyOfRange(seq,right-1, left+1);
System.out.println(Arrays.toString(res));
System.out.println(right-1);
System.out.println(left);
System.out.println(notfound);
return 0;
}