Java Solution using Regex (to tackle leading zeroes)


  • 0
    H

    If the number of digits to remove (k) is more than the length of the number, we simply return 0.
    We need to find the pattern that that the digit of the left is greater than the one on its right. This is a greedy approach. Removing that greater value digit will result in a number of smaller value. We do this task k times.
    After that, we may have been left with a number with leading zeroes. That is removed using regex. Finally, if the resultant number is empty, we return 0, else the resultant string.

    • Time Complexity: O(kn)
    • Space Complexity: O(n)
    public String removeKdigits(String num, int k) 
    	{	
    		if(num == null || num.length() == 0 || k >= num.length())
    			return "0";
    		
    		StringBuilder numBuilder = new StringBuilder(num);
    		int l = 0;
    		
    		while(k > 0)
    		{	
    			l = numBuilder.length();
    			int i = 0;
    			while(i < l-1 && numBuilder.charAt(i) <= numBuilder.charAt(i+1))
    				i++;
    			
    			numBuilder.deleteCharAt(i);
    			k--;
    		}
    		
    		//remove leading 0s
    		num = numBuilder.toString().replaceFirst("^0+", "");
    		
    		//if all the leading 0s removal makes the resultant blank, return 0
            return num.equals("") ? "0" : num;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.