欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

String Compression(C++压缩字符串)

程序员文章站 2022-03-12 19:45:35
...

解题思路:

(1)既然要使用原地算法,那么这里设置三个指针i,start,end

(2)i表示当前字符串的位置,start表示目标字符串的末尾,end用来判断连续相等字符的迭代

class Solution {
public:
    int compress(vector<char>& chars) {
        int i=0,start=0,end,count;
        string str;
        while(i<chars.size()) {
	    if(i+1<chars.size()) {
		if(chars[i]!=chars[i+1]) {
		    chars[start]=chars[i];
		    i++;
		    start++;
		}
		else {
		    chars[start]=chars[i];
		    end = i+1;
		    count = 1;
		    while(end<chars.size()&&chars[i]==chars[end]) {
			end++;
			count++;
		    }
		    str = to_string(count);
		    for(auto&& c:str) chars[++start]=c;
		    i=end;
		    start++;
                }
	    } else {
		chars[start]=chars[i];
		i++;
		start++;
	    }
	}
	//chars.erase(chars.begin()+start,chars.end());
	//return chars.size()
	return start;
    }
};

(3)LintCode

class Solution {
public:
    /**
     * @param originalString: a string
     * @return: a compressed string
     */
    string compress(string &chars) {
        int i=0,end,count;
        string str="";
        while(i<chars.length()) {
	    if(i+1<chars.length()) {
		if(chars[i]!=chars[i+1]) {
		    str = str + chars[i];
		    str = str + '1';
		    i++;
		}
                else {
		    str = str + chars[i];
		    end = i+1;
		    count = 1;
		    while(end<chars.length()&&chars[i]==chars[end]) {
			end++;
			count++;
		    }
		    str = str + to_string(count);
		    i=end;
		}
	    } else {
		str = str + chars[i];
		if(i!=chars.length()-1) str = str + '1';
		i++;
	    }
	}
	return str.length()<chars.length()?str:chars;
    }
};