1. 程式人生 > >443. String Compression的C++解法

443. String Compression的C++解法

題目描述:https://leetcode.com/problems/string-compression/

看清題目要求:1.在原字串上替換
                         2.單獨一個字元不用加數字
                         3.最後返回替換後字串的長度

直接在原字串上替換需要三個變數:i是讀取的字元首位置,j是相同字元的最後位置+1(利用i,j統計某字元出現的次數),next記錄新字串下一個將要新增的位置。

class Solution {
public:
	int compress(vector<char>& chars) {
		if (chars.size()==0) return 0;
		if (chars.size()==1) return 1;
		int i = 0;
		int next = 0;
		while (i<chars.size())
		{
			int j = i;
			while (j<chars.size() && chars[j] == chars[i]) j++;
			chars[next] = chars[i];
			string tmp = to_string(j - i);
			if (j - i>1)
			{ string tmp = to_string(j - i);
			for (int k = 0; k<tmp.size(); k++)
				chars[next + k + 1] = tmp[k]; next = next + tmp.size()+1;
			}
			else next++;
			i = j;
		}
		return next;
	}
};