了解code,去除字符串中的重复字符(破解编码采访)字符串、字符、采访、code

2023-09-11 23:24:29 作者:大爹呦@

下面是破解编码访谈Q1.3设计一个算法,写code删除字符串中的重复的字符,而无需使用任何额外的缓冲注意的问题:一个或两个额外的变量都很好该阵列的额外副本是没有的。我写了一个程序,似乎运作良好,但我很困惑,我自己的计划。这里是code连接。

Here is the question from "cracking the coding interview" Q1.3 "Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra copy of the array is not." and I wrote a program that seems to work well, but I am confused with my own program. Here is the code attached.

string remove_duplicates(string &s1)
{
   int n=s1.size();
   for(int i=n-1; i!=-1; --i)
        for(int j=0; j<i; ++j)
        {
            if(s1[i]==s1[j])
            {
                int k=i;
                while(k!=n)
                {
                    s1[k]=s1[k+1];
                    k++;
                }
            }
        }
    return s1;
}

如果S1 = abcdeafg,输出会使用此code ABCDEFG,(如果输入的是ABABABAB,输出为AB) 但是,我认为是,因为S1的长度不改变,输出应该是abcdefga,因为我只是移动第二个'a'到S1的结束。请问你们能帮我解释一下吗?

If s1=abcdeafg, the output will be abcdefg by using this code, (and if input is abababab, output will be ab) But what I thought is that because the length of s1 does not change, the output should be abcdefga since I just move the second 'a' to the end of s1. Could you guys help me explain it?

推荐答案

S1的长度实际上正在发生变化。当你找到一个重复的特性和使用,而(K!= n)的循环走向S1的结尾重复字符,在循环的最后一次迭代当k = = N-1时,code是评价S1 [N-1] = S1 [n]和实际上是S1 [N-1] ='\ 0',所以s1的长度由1缩短。

The length of s1 actually is changing. When you have found a duplicate character and are using the while(k!=n) loop moving the duplicate character towards the end of s1, in the final iteration of the loop when k == n-1, the code is evaluating s1[n-1] = s1[n] and actually is s1[n-1] = '\0', so the length of s1 is shortened by 1.