-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmallestStringLength.java
More file actions
29 lines (23 loc) · 903 Bytes
/
SmallestStringLength.java
File metadata and controls
29 lines (23 loc) · 903 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.util.Scanner;
import java.util.Stack;
public class SmallestStringLength {
public static int findSmallestLength(String input) {
Stack<Character> stack = new Stack<>();
for (char c : input.toCharArray()) {
if (!stack.isEmpty() && stack.peek() == '0' && c == '1') {
stack.pop(); // Remove "0" and "1" if adjacent
} else {
stack.push(c);
}
}
return stack.size();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string containing 0, 1, and *: ");
String inputString = scanner.nextLine();
int smallestLength = findSmallestLength(inputString);
System.out.println("Length of the smallest string after operations: " + smallestLength);
// scanner.close();
}
}