given a string s, in one operation we can delete any occurences of geek as a substring in the string. find the number of delete operations you have to perform to make the string empty.
Mohammed
Guys, does anyone know the answer?
get given a string s, in one operation we can delete any occurences of geek as a substring in the string. find the number of delete operations you have to perform to make the string empty. from screen.
How to Remove the Last Character of a String?
Learn how to remove the last character of a String with core Java or using external libraries.
How to Remove the Last Character of a String?
Last modified: March 16, 2023
Written by: baeldung
Java+ Java String
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
> CHECK OUT THE COURSE
1. Overview
In this quick tutorial, we're going to explore different techniques for removing the last character of a String.
2. Using String.substring()
The easiest way is to use the built-in substring() method of the String class.
In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character. We can achieve that by calling String‘s length() method, and subtracting 1 from the result.
However, this method isn't null-safe, and if we use an empty string, this is going to fail.
To overcome issues with null and empty strings, we can wrap the method in a helper class:
public static String removeLastChar(String s) {
return (s == null || s.length() == 0)
? null
: (s.substring(0, s.length() - 1));
}
We can refactor the code, and use Java 8:
public static String removeLastCharOptional(String s) {
return Optional.ofNullable(s)
.filter(str -> str.length() != 0)
.map(str -> str.substring(0, str.length() - 1))
.orElse(s); }
3. Using StringUtils.substring()
Instead of reinventing the wheel, we can use the StringUtils class from the Apache Commons Lang3 library, which offers helpful String operations. One of them is a null-safe substring() method, which handles exceptions.
To include StringUtils, we have to update our pom.xml file:
StringUtils.substring() requires three parameters: a given String, an index of the first character (in our case it will be 0 always), and the index of the penultimate character. Again, we can simply use the length() method and subtract 1:
String TEST_STRING = "abcdef";
StringUtils.substring(TEST_STRING, 0, TEST_STRING.length() - 1);
Yet again, this operation isn't null-safe. It'll work fine with empty Strings though.
4. Using StringUtils.chop()
The StringUtils class provides the chop() method, which works well with all edge scenarios: empty and null Strings.It's very easy to use, and requires only one parameter: the String. Its sole purpose is to remove the last character, nothing more, nothing less:
StringUtils.chop(TEST_STRING);
5. Using Regular Expression
We can also remove the last character (or any number of characters) from a String by making good use of regular expressions.
For example, we can use the replaceAll() method of the String class itself, which takes two parameters: the regular expression and the replacement String:
TEST_STRING.replaceAll(".$", "");
Note that, because we're calling a method on the String, the operation isn't null-safe.
Also, replaceAll() and regex expressions can be complex at first sight. We can read more about regex here, but to make the logic a bit more user-friendly, we can wrap it in a helper class:
public static String removeLastCharRegex(String s) {
return (s == null) ? null : s.replaceAll(".$", "");
}
Note that if a String ends with a newline, then the above method will fail as “.” in regex matches for any character except for line terminators.
Finally, let's re-write the implementation with Java 8:
public static String removeLastCharRegexOptional(String s) {
return Optional.ofNullable(s)
.map(str -> str.replaceAll(".$", ""))
.orElse(s); }
6. Conclusion
In this brief article, we discussed different ways of removing only the last character of a String, some manual and some ready out of the box.
If we need more flexibility, and we need to remove more characters, we can use the more advanced solution with regular expressions.
As always, the code used throughout the article can be found over on GitHub.
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
>> CHECK OUT THE COURSELearning to build your API
with Spring?Download the E-book
Remove All Occurrences of a Substring
Can you solve this real interview question? Remove All Occurrences of a Substring - Given two strings s and part, perform the following operation on s until all occurrences of the substring part are removed: * Find the leftmost occurrence of the substring part and remove it from s. Return s after removing all occurrences of part. A substring is a contiguous sequence of characters in a string. Example 1: Input: s = "daabcbaabcbc", part = "abc" Output: "dab" Explanation: The following operations are done: - s = "daabcbaabcbc", remove "abc" starting at index 2, so s = "dabaabcbc". - s = "dabaabcbc", remove "abc" starting at index 4, so s = "dababc". - s = "dababc", remove "abc" starting at index 3, so s = "dab". Now s has no occurrences of "abc". Example 2: Input: s = "axxxxyyyyb", part = "xy" Output: "ab" Explanation: The following operations are done: - s = "axxxxyyyyb", remove "xy" starting at index 4 so s = "axxxyyyb". - s = "axxxyyyb", remove "xy" starting at index 3 so s = "axxyyb". - s = "axxyyb", remove "xy" starting at index 2 so s = "axyb". - s = "axyb", remove "xy" starting at index 1 so s = "ab". Now s has no occurrences of "xy". Constraints: * 1 <= s.length <= 1000 * 1 <= part.length <= 1000 * s and part consists of lowercase English letters.
class Solution { public:
string removeOccurrences(string s,
string part) { } };
Minimum steps to delete a string by deleting substring comprising of same characters
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
Minimum steps to delete a string by deleting substring comprising of same characters
Difficulty Level : Hard
Last Updated : 18 Jun, 2022
Read Discuss Courses Practice Video
Given string str. You are allowed to delete only some contiguous characters if all the characters are the same in a single operation. The task is to find the minimum number of operations required to completely delete the string.
Examples:Input: str = “abcddcba”Output: 4Delete dd, then the string is “abccba”
Delete cc, then the string is “abba”
Delete bb, then the string is “aa”
Delete aa, then the string is null.
Input: str = “abc”Output: 3Recommended: Please try your approach on first, before moving on to the solution.
Approach: The problem can be solved using Let dp[l][r] be the answer for sub-string s[l, l+1, l+2, …r]. Then we have two cases:The first letter of the sub-string is deleted separately from the rest, then dp[l][r] = 1 + dp[l+1][r].
The first letter of the sub-string is deleted alongside with some other letter (both letters must be equal), then dp[l][r] = dp[l+1][i-1] + dp[i][r], given that l ≤ i ≤ r and s[i] = s[l].
The following two cases can be recursively called along with memoization to avoid repetitive function calls.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#includeusing namespace std;
const int N = 10;
// Function to return the minimum number of
// delete operations
int findMinimumDeletion(int l, int r, int dp[N][N], string s)
{ if (l > r) return 0; if (l == r) return 1; if (dp[l][r] != -1) return dp[l][r];
// When a single character is deleted
int res = 1 + findMinimumDeletion(l + 1, r, dp, s);
// When a group of consecutive characters
// are deleted if any of them matches
for (int i = l + 1; i <= r; ++i) {
// When both the characters are same then
// delete the letters in between them
if (s[l] == s[i])
res = min(res, findMinimumDeletion(l + 1, i - 1, dp, s)
+ findMinimumDeletion(i, r, dp, s));
} // Memoize
return dp[l][r] = res;
} // Driver code int main() {
string s = "abcddcba";
int n = s.length(); int dp[N][N];
memset(dp, -1, sizeof dp);
cout << findMinimumDeletion(0, n - 1, dp, s);
return 0; }
Java
Python3
C#
PHP
Java Python3 C# PHP Javascript
Output:4
Time Complexity: O(N*N), as we are using a loop to traverse N times and in each traversal we are recursively calling the function which will cost O(N) time. Where N is the length of the string.Auxiliary Space: O(N*N), as we are using extra space for the dp matrix. Where N is the length of the string.
Guys, does anyone know the answer?