Tuesday, July 14, 2015

Delete Digits

Delete Digits

16%
Accepted
Given string A representative a positive integer which has N digits, remove any k digits of the number, the remaining digits are arranged according to the original order to become a new positive integer.
Find the smallest integer after remove k digits.
N <= 240 and k <= N,
Have you met this question in a real interview? 
Yes
Example
Given an integer A = "178542", k = 4
return a string "12"
public class Solution {
    /**
     *@param A: A positive integer which has N digits, A is a string.
     *@param k: Remove k digits.
     *@return: A string
     */
    public String DeleteDigits(String A, int k) {
        // write your code here
        
        for(int i = 1; i < A.length() && k > 0;){
            if(A.charAt(i) < A.charAt(i-1)){
                A = A.substring(0, i-1) + A.substring(i);
                k--;
                if(i > 1)
                    i--;
            } else i++;
        }
       int beg = 0;
       for(int i = 0 ; i < A.length(); i++){
           if(A.charAt(i) == '0'){
               beg++;
           } else break;
       }
        
        return A.substring(beg, A.length() - k);
    }
}

2 comments:

  1. Code is Not Correct,

    Not Working For 90249, 2
    ans :- 24
    but it's giving 249

    ReplyDelete
  2. 2 is the number of digit we need to delete.

    ReplyDelete