Separate the string such that no groups will have same letters (#32)

pull/33/head
kumarvishek 2021-01-27 19:38:29 +05:30 committed by GitHub
parent e65d168ef6
commit 3a1a05fc08
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 35 additions and 0 deletions

View File

@ -0,0 +1,35 @@
//Separate the strings such as in other group same letter does not repeat.
//Example abcdaef will give 5,1,1 from first 'a' to last 'a' one group and then remaining 2 letters from 1-1 group
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class SplitString {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string");
String s = sc.next();
List<Integer> a = new ArrayList<Integer>();
Map<Character, Integer> last = new HashMap<Character, Integer>();
for (int i = 0; i < s.length(); i++) {
last.put(s.charAt(i), i);
}
int p = 0, ctr = 0;
for (int i = 0; i < s.length(); i++) {
if (last.get(s.charAt(i)) > p)
p = last.get(s.charAt(i));
++ctr;
if (i == p) {
a.add(ctr);
ctr = 0;
}
}
for (Integer i : a) {
System.out.println(i);
}
sc.close();
}
}