LeetCode 402. Remove K Digits

1.題目

402. Remove K Digits
Given a non-negative integer num represented as a string, remove k digits from the number so that the new number is the smallest possible.

Note:
The length of num is less than 10002 and will be ≥ k.
The given num does not contain any leading zero.
Example 1:

Input: num = "1432219", k = 3
Output: "1219"
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
Example 2:

Input: num = "10200", k = 1
Output: "200"
Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
Example 3:

Input: num = "10", k = 2
Output: "0"
Explanation: Remove all the digits from the number and it is left with nothing which is 0.
題目大意:從給出的數字組成的字符串中刪去k個數字字符,使其值最小。(不能改變原始字符的相對順序)

2.解題思路

 採取StringBuffer存儲字符串,因爲其對字符的操作比較簡便。
1)由字符串第一位數字不是0,若其後第二位開始有連續的0值出現,則直接刪除第一位數,可達到一下子消滅多位數的效果。(且僅限第一個字符可以這樣)
2)若第一位數後不是0,則需要去挨個比較當前字符與前一個字符的大小
若當前字符小於前一個字符,則直接刪除前一個字符 ,如1432219中 出現下降轉折的就有4 3 2;(遵守不改變原字符順序的情況下刪除當前子段中最大的字符,即貪心原則);
若當前字符不小於前一個字符,則直接往後進行遍歷;
3)我們在進行刪除的時候要統計當前刪除的字符個數count,在循環結束後要拿出來與k值對比
若count=k,則說明數字字符串已經在遍歷的時候就刪除完成;
若count<k,則說明原字符串或其截取後的子串一定是一個遞增不減的序列,如12333344這種,故此時我們只需要在該字符串的最後刪除k-count個字符即可;

3.JAVA代碼

    public String removeKdigits(String num, int k) {
    	int len = num.length();
    	if(k == len)
    		return "0";
    	if(k == 0)
    		return num;
    	StringBuffer sb = new StringBuffer(num);
    	int count = 0; //記錄當前刪除字符的個數
    	//循環k次,每次旨在刪除一個字符
    	for(int i=0;i<k;i++){
    		//由於字符串放在StringBuffer中,則當 第一位數被刪除後,就會有後面的數頂上,所以每次循環時都應該判斷第一位數的情況
        	if(sb.charAt(1) == '0'){
        		//按照思路1),將第一位數和其後連續的所有0值全部刪除
        		int firstNotZero = 1;
        		while(firstNotZero<sb.length()&&sb.charAt(firstNotZero)=='0')
        			firstNotZero++;
        		sb.delete(0, firstNotZero);
        		count++;
        	}else{
        		//按照思路2),尋找“轉折數”然後直接刪除
            	for(int j=1;j<sb.length();j++){
            		if(sb.charAt(j)-'0' < sb.charAt(j-1)-'0'){
            			sb.deleteCharAt(j-1);
            			count++;
            			break;
            		}
            	}
        	}
    	}
    	//當上面循環沒能達到刪除次數時,表明此時的StringBuffer中的字符串已經是遞增不減的,刪除最後k-count字符即可
    	if(count < k){
    		sb.delete(sb.length()-(k-count), sb.length());
    	}
    	if(sb.length() == 0)
    		return "0";
        return  sb.toString();
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章