Implementing String Reversal and Character Replacement Algorithms in Java
344. Reverse String
Write a functon that reverses an input string. The string is provided as a character array s.
You must modify the input array in-place and use only O(1) extra memory.
Example 1:
Input: s = ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Solution: Use a two-pointer approach. Initialize pointers at both ends of the array and swap characters while moving towards the center.
Implementation:
public class ReverseString {
public void reverse(char[] chars) {
int start = 0;
int end = chars.length - 1;
while (start < end) {
char tmp = chars[end];
chars[end] = chars[start];
chars[start] = tmp;
start++;
end--;
}
}
}
541. Reverse String II
Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string.
If there are fewer than k characters left, reverse all of them. If there are between k and 2k characters left, reverse the first k characters and leave the rest as is.
Example 1:
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Solution: Process the string in segments of length 2k. For each segment, reverse its first k characters. When dealing with strings in fixed intervals, consider adjusting the loop increment accordingly.
Implementation:
public class ReverseStringII {
public String reverseSegments(String str, int k) {
char[] arr = str.toCharArray();
for (int idx = 0; idx < arr.length; idx += 2 * k) {
int left = idx;
int right = Math.min(arr.length - 1, idx + k - 1);
while (left < right) {
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
return new String(arr);
}
}
54. Replace Digits
Given a string s consisting of lowercase letters and digits, write a function that keeps letters unchanged and replaces each digit with the word "number".
Example: For input "a1b2c3", the output should be "anumberbnumbercnumber".
Solution: Convert the string to a mutable sequence like StringBuilder to efficiently append characters or replacement strings. Use Character.isDigit() to identify numeric characters.
Implementation:
import java.util.Scanner;
public class DigitReplacer {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String original = input.nextLine();
StringBuilder result = new StringBuilder();
for (int pos = 0; pos < original.length(); pos++) {
char current = original.charAt(pos);
if (Character.isDigit(current)) {
result.append("number");
} else {
result.append(current);
}
}
System.out.println(result.toString());
}
}