leetcode- string compression face questions 01.06

String compression. Using the number of recurring characters, written in a way to achieve the basic string compression. For example, the string aabcccccaaa becomes a2b1c5a3. If the string "compressed" not shorter, the original string is returned. You may assume the string contains only the case letters (a to z).

Thinking

Are equal before and after the double pointer is determined, equal number plus one. Details of how that exist after the new character string into the number of characters, how int variables into a string here not to use library functions itoa, so we can first determine the number of integer digits, and each character is stored in reverse order, by + '0' in this way the integer units into character form, and then stored in an array of characters. It is important to consider the basic types of overflow, if the number of repeated characters is too large, there may be plastic overflow, but the problem is given no more than 5w characters, so this problem does not exist. But I think before the direct use of char type to define count, defined as a '1' in this form, was not any change, resulting in a test case has not passed, but later found, the char type overflows, memory error occurred.

char* compressString(char* s){
    int len=strlen(s);
    char* new_s=(char*) malloc(sizeof(char)* (len*2+1));
    if(*s=='\0') return "";
    char ch=s[0];
    int index=0;
    int count=1;	//这里,之前用的char count=1; 导致有一个case一直不通过
    for(int i=1;i<=len;i++){		
        if(ch==s[i]){			//之前指针与当前指针比较,灵活运用for循环
            count++;
        }
        else{
            new_s[index++]=ch;
            int num=(int) log10(count),num1=num;		//计算位数,倒序存入数组
            while(count){
                new_s[index+num]=count%10+'0';
                count/=10;
                num--;
            }
            index+=num1+1;
            count=1;
            ch=s[i];
        }
    }
    new_s[index]='\0';
    if(len>index){
         return new_s;
    }
    return s;
}
Published 19 original articles · won praise 1 · views 3124

Guess you like

Origin blog.csdn.net/qq_41603639/article/details/104897024