给定数字字符串str ,任务是从给定字符串删除所有前导零。如果字符串只包含零,则打印一个“0” 。
例子:
Input: str = “0001234”
Output: 1234
Explanation:
Removal of leading substring “000” modifies the string to “1234”.
Hence, the final answer is “1234”.
Input: str = “00000000”
Output: 0
Explanation:
There are no numbers except 0
天真的方法:
解决该问题的最简单的方法是遍历字符串高达第一非零字符存在的字符串中的,并存储从该索引作为回答起始的剩余字符串。如果遍历整个字符串,则意味着字符串中的所有字符都是‘0’ 。对于这种情况,存储“0”作为答案。打印最终答案。
时间复杂度: O(N)
辅助空间: O(N)
节省空间的方法:
请按照以下步骤使用正则表达式解决常量空间中的问题:
- 创建如下所示的正则表达式以删除前导零
regex = “^0+(?!$)”
where:
^0+ match one or more zeros from the beginning of the string.
(?!$) is a negative look-ahead expression, where “$” means the end of the string.
- 使用 String 类的内置 replaceAll() 方法,该方法接受两个参数,一个正则表达式和一个替换字符串。
- 要删除前导零,请将Regex作为第一个参数传递,将空字符串作为第二个参数传递。
- 此方法用给定的字符串替换匹配的值。
下面是上述方法的实现:
C++
// C++ Program to implement
// the above approach
#include
#include
using namespace std;
// Function to remove all leading
// zeros from a a given string
void removeLeadingZeros(string str)
{
// Regex to remove leading
// zeros from a string
const regex pattern("^0+(?!$)");
// Replaces the matched
// value with given string
str = regex_replace(str, pattern, "");
cout << str;
}
// Driver Code
int main()
{
string str = "0001234";
removeLeadingZeros(str);
return 0;
}
Java
// Java Program to implement
// the above approach
import java.util.regex.*;
class GFG
{
// Function to remove all leading
// zeros from a a given string
public static void removeLeadingZeros(String str)
{
// Regex to remove leading
// zeros from a string
String regex = "^0+(?!$)";
// Replaces the matched
// value with given string
str = str.replaceAll(regex, "");
System.out.println(str);
}
// Driver Code
public static void main(String args[])
{
String str = "0001234";
removeLeadingZeros(str);
}
}
Python3
# Python3 Program to implement
# the above approach
import re
# Function to remove all leading
# zeros from a a given string
def removeLeadingZeros(str):
# Regex to remove leading
# zeros from a string
regex = "^0+(?!$)"
# Replaces the matched
# value with given string
str = re.sub(regex, "", str)
print(str)
# Driver Code
str = "0001234"
removeLeadingZeros(str)
# This code is contributed by avanitrachhadiya2155
C#
// C# program to implement
// the above approach
using System;
using System.Text.RegularExpressions;
class GFG{
// Function to remove all leading
// zeros from a a given string
public static void removeLeadingZeros(string str)
{
// Regex to remove leading
// zeros from a string
string regex = "^0+(?!$)";
// Replaces the matched
// value with given string
str = Regex.Replace(str, regex, "");
Console.WriteLine(str);
}
// Driver Code
public static void Main(string[] args)
{
string str = "0001234";
removeLeadingZeros(str);
}
}
// This code is contributed by ukasp
1234
时间复杂度: O(N),其中 N 是字符串的长度。
辅助空间: O(1)
特定于Java 的方法:请参阅本文以了解使用 StringBuffer 的特定于 Java 的方法。
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live