From 3a1a05fc08fefa2f5925130dc76ffcbce071986c Mon Sep 17 00:00:00 2001 From: kumarvishek <40957579+kumarvishek@users.noreply.github.com> Date: Wed, 27 Jan 2021 19:38:29 +0530 Subject: [PATCH] Separate the string such that no groups will have same letters (#32) --- strings/java/SplitString.java | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 strings/java/SplitString.java diff --git a/strings/java/SplitString.java b/strings/java/SplitString.java new file mode 100644 index 00000000..24b67cf4 --- /dev/null +++ b/strings/java/SplitString.java @@ -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 a = new ArrayList(); + Map last = new HashMap(); + 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(); + } +} \ No newline at end of file