Emerson is very fond of strings, and he keeps trying to reverse them. His mother gives…
- User
Emerson is very fond of strings, and he keeps trying to reverse them. His mother gives him two binary strings and asks him to convert the binary string str1 into str2 by applying the following rules: Step 1: Reverse any substring of length 2 (of str1) and get str1' (str1' = str1"). Step 2: Reverse any substring of length 3 (of str1) and get str1" (str1" = str1"'). Step 3: Reverse any substring of length 4 (of str1) and get str1'" (str1'" = str1""). Step 4, Step 5 and so on. Write an algorithm to help Emerson convert the binary string str1 into str2, in the minimum number of steps.
Input: The first line of the input consists of a binary string - str1. The second line consists of a binary string - str2.
Output: Print an integer representing the minimum number of steps required to convert str1 into str2. If there is no such way of conversion, then print "-1".
Constraints: 2 <= N <= 30, where N is the length of the strings.
Note: At any step Emerson can reverse only one substring. The strings str1 and str2 consist of only 0s and 1s.
Example: Input: 1010 0011
Output: 2
Explanation: Step 1: String str1 -> 1010 -> 1001 (Reverse substring of length 2) Step 2: String str1' -> 1001 -> 0011 (Reverse substring of length 3) String str1 is converted to String str2 in two steps, so the output is 2.
Example: Input: 10101010 00101011
Output: 4 import java.util.*;
public class Main { static int minSteps(String str1, String str2) { if (str1.equals(str2)) return 0;
HashMap<String, Integer> visited = new HashMap<>(); Queue<String> queue = new LinkedList<>(); queue.add(str1); visited.put(str1, 0); while (!queue.isEmpty()) { String current = queue.poll(); int steps = visited.get(current); // Try all possible reversals for (int len = 2; len <= current.length(); len++) { for (int i = 0; i + len <= current.length(); i++) { String next = reverseSubstring(current, i, i + len); if (!visited.containsKey(next)) { visited.put(next, steps + 1); queue.add(next); if (next.equals(str2)) { return steps + 1; } } } } } return -1; } static String reverseSubstring(String str, int start, int end) { char[] chars = str.toCharArray(); while (start < end - 1) { char temp = chars[start]; chars[start] = chars[end - 1]; chars[end - 1] = temp; start++; end--; } return new String(chars); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str1 = scanner.nextLine(); String str2 = scanner.nextLine(); System.out.println(minSteps(str1, str2)); scanner.close(); }} for second example this code is giving me output as 2 it should come 4
- Assistant