【问题标题】:String Formatting using C / C++使用 C/C++ 格式化字符串
【发布时间】:2013-10-26 13:06:03
【问题描述】:

最近我在一次采访中被要求将字符串“aabbbccccdddd”转换为“a2b3c4d5”。目标是用一次出现和重复计数替换每个重复的字符。这里'a'在输入中重复了两次,所以我们必须在输出中将它写为'a2'。我还需要编写一个函数来将格式反转回原来的格式(例如从字符串“a2b3c4d5”到“aabbbccccddddd”)。我可以随意使用 C 或 C++。我写了下面的代码,但面试官似乎对此不太满意。他让我尝试比这更聪明的方法。

在下面的代码中,我使用formatstring() 通过添加重复计数来消除重复字符,并使用reverseformatstring() 转换回原始字符串。

void formatstring(char* target, const char* source) {
  int charRepeatCount = 1;
  bool isFirstChar = true;
  while (*source != '\0') {
    if (isFirstChar) {
      // Always add the first character to the target
      isFirstChar = false;
      *target = *source;
      source++; target++;
    } else {
      // Compare the current char with previous one,
      // increment repeat count
      if (*source == *(source-1)) {
        charRepeatCount++;
        source++;
      } else {
        if (charRepeatCount > 1) {
          // Convert repeat count to string, append to the target
          char repeatStr[10];
          _snprintf(repeatStr, 10, "%i", charRepeatCount);
          int repeatCount = strlen(repeatStr);
          for (int i = 0; i < repeatCount; i++) {
            *target = repeatStr[i];
            target++;
          }
          charRepeatCount = 1; // Reset repeat count
        }
        *target = *source;
        source++; target++;
      }
    }
  }
  if (charRepeatCount > 1) {
    // Convert repeat count to string, append it to the target
    char repeatStr[10];
    _snprintf(repeatStr, 10, "%i", charRepeatCount);
    int repeatCount = strlen(repeatStr);
    for (int i = 0; i < repeatCount; i++) {
      *target = repeatStr[i];
      target++;
    }
  }
  *target = '\0';
}

void reverseformatstring(char* target, const char* source) {
  int charRepeatCount = 0;
  bool isFirstChar = true;
  while (*source != '\0') {
    if (isFirstChar) {
      // Always add the first character to the target
      isFirstChar = false;
      *target = *source;
      source++; target++;
    } else {
      // If current char is alpha, add it to the target
      if (isalpha(*source)) {
        *target = *source;
        target++; source++;
      } else {
        // Get repeat count of previous character
        while (isdigit(*source)) {
          int currentDigit = (*source) - '0';
          charRepeatCount = (charRepeatCount == 0) ?
              currentDigit : (charRepeatCount * 10 + currentDigit);
          source++;
        }
        // Decrement repeat count as we have already written
        // the first unique char to the target
        charRepeatCount--; 
        // Repeat the last char for this count
        while (charRepeatCount > 0) {
          *target = *(target - 1);
          target++;
          charRepeatCount--;
        }
      }
    }
  }
  *target = '\0';
}

我没有发现上述代码有任何问题。还有其他更好的方法吗?

【问题讨论】:

  • 请记住,这可能是面试官最喜欢的问题,并且可能已经考虑了几个月。
  • 除了奇怪的缩进样式,我觉得没什么不好的。我想我会以几乎相同的方式做到这一点。
  • @H2CO3,抱歉缩进错误,感谢您的回复。
  • @Prabu 不,我不认为交叉发布是个好主意。现在保持原样,这只是您下次考虑提出类似问题时的建议。
  • 如果我在面试中问到这个问题,我会对提出先编写反向解决方案的候选人印象深刻。这是因为它更简单(除了知道目标字符串的大小)并且为更困难的压缩提供了一个测试框架。

标签: c++ c visual-c++


【解决方案1】:

方法/算法很好,也许您可​​以稍微改进和缩小代码(通过做一些更简单的事情,没有必要以过于复杂的方式解决这个问题)。并选择一种真正有意义的缩进样式。

A C 解决方案:

void print_transform(const char *input)
{
    for (const char *s = input; *s;) {
        char current = *s;
        size_t count = 1;
        while (*++s == current) {
            count++;
        }

        if (count > 1) {
            printf("%c%zu", current, count);
        } else {
            putc(current, stdout);
        }
    }

    putc('\n', stdout);
}

(这可以很容易地修改,以便它返回转换后的字符串,或者将其写入足够长的缓冲区。)

C++ 解决方案:

std::string transform(const std::string &input)
{
    std::stringstream ss;
    std::string::const_iterator it = input.begin();

    while (it != input.end()) {
        char current = *it;
        std::size_t count = 1;
        while (++it != input.end() && *it == current) {
            count++;
        }

        if (count > 1) {
            ss << current << count;
        } else {
            ss << current;
        }
    }

    return ss.str();
}

【讨论】:

  • 感谢这么简单的方法。
  • @Prabu 另请参阅 C++ 解决方案。 (并且永远记住:只有一件事比可读性和简单性更重要,那就是正确性。其他一切(例如性能、“聪明”等)的优先级都低于可读性。无论何时,都应该采用幼稚的实现你可以。
  • 朴素的实现很好。只要你使用语言的习语。不要编写 C 代码并声称这是好的 C++。也很简单,您可以谈论它并提出改进建议。如果面试官想要一个优化的版本,你总是可以在第二次迭代中做到这一点。
  • @LokiAstari 我没有声称 C 版本是好的 C++,这就是我添加 C++ 的原因。但是,是的,其他点是对的!
  • @H2CO3:没有指向您的代码。只是对一般的面试提出一点看法。 :-)
【解决方案2】:

由于其他几个人提出了非常合理的替代方案,我想就我认为您的潜在问题提供一些意见:“他让我尝试比这更聪明的方法......还有其他更好的方法吗?这样做?”

当我采访一位开发人员时,我正在寻找能告诉我她如何解决问题的信号:

  1. 最重要的是,正如 H2CO3 所指出的,正确性:代码可以工作吗?如果算法合理,我通常很乐意忽略小的语法错误(忘记分号、不匹配的括号或大括号等)。

  2. 正确使用语言,尤其是在候选人声称拥有专业知识或拥有丰富经验的情况下。他是否理解并恰当地使用习语来编写简单明了的代码?

  3. 她能解释一下她在制定解决方案时的思路吗?它是合乎逻辑和连贯的,还是一种霰弹枪方法?她是否能够并愿意进行良好的沟通?

  4. 他是否考虑了极端情况?如果是这样,内在算法是否处理它们,或者一切都是特殊情况?尽管如果初始算法对所有情况都“有效”,我最高兴,但我认为从涵盖所有情况的详细方法开始是完全可以接受的(或者只是添加“TODO”注释,并指出需要做更多的工作完成),然后再进行简化,以便更容易注意到模式或重复代码。

  5. 她是否考虑过错误处理?通常,如果候选人首先询问她是否可以假设输入是有效的,或者是这样的评论,“如果这是生产代码,我会检查 x, y em> 和 z 问题,”我会问她会做什么,然后建议她现在专注于一个有效的算法,然后(也许)稍后再回来。但如果候选人没有提及,我会很失望。

  6. 测试,测试,测试!候选人将如何验证他的代码是否有效?他是遍历代码并建议测试用例,还是我需要提醒他?测试用例是否合理?他们会覆盖边缘情况吗?

  7. 优化:作为最后一步,一切正常并经过验证后,我有时会询问候选人是否可以改进她的代码。如果她在没有我催促的情况下提出建议,则可以加分;如果她在代码运行之前花费大量精力担心它,就会产生负面影响。


将这些想法应用到您编写的代码中,我会做出以下观察:

适当地使用const 是一个加分项,因为它表明您熟悉该语言。在面试中,我可能会问一两个关于为什么/何时使用它的问题。

在整个代码中正确使用char 指针是一个好兆头。我倾向于在比较中明确数据类型,特别是在采访中,所以我很高兴看到,例如 while (*source != '\0') 而不是(常见的,正确的,但 IMO 不太小心)while(*source)。

isFirstChar 有点危险,基于我的“边缘情况”点。当您声明一个布尔值来跟踪代码的状态时,通常有一种方法可以重新构建问题以从本质上处理条件。在这种情况下,您可以使用charRepeatCount 来确定这是否是可能系列中的第一个字符,因此您无需显式测试字符串中的第一个字符。

同理,重复的代码也可以是算法可以简化的标志。一项改进是将charRepeatCount 的转换移至单独的函数。请参阅下文以获得更好的解决方案。

这很有趣,但我发现候选人很少在面试期间将 cmets 添加到他们的代码中。对有帮助的人表示敬意,对那些在没有信息的情况下增加冗长的“增加计数器”之类的人给予负面评价。人们普遍认为,除非您正在做一些奇怪的事情(在这种情况下,您应该重新考虑您所编写的内容),否则您应该假设阅读您的代码的人熟悉编程语言。所以 cmets 应该解释你的思考过程,而不是把代码翻译成英文。

嵌套条件或循环的过多级别也可能是一个警告。您可以通过将每个字符与下一个而不是前一个字符进行比较来消除一层嵌套。这甚至适用于字符串中的最后一个字符,因为它将与终止的空字符进行比较,后者不会匹配并且可以像任何其他字符一样对待。

有更简单的方法可以将 charRepeatCount 从 int 转换为字符串。例如,_snprintf() 将其“打印”到字符串的字节数返回,因此您可以使用
target += _snprintf(target, 10, "%i", charRepeatCount);

在反转函数中,您已经完美地使用了三元运算符......但没有必要对零值进行特殊处理:无论其值如何,数学都是相同的。同样,还有一些标准的实用函数,例如 atoi(),可以为您将字符串的前导数字转换为整数。

经验丰富的开发人员通常会将递增或递减操作作为循环条件的一部分,而不是作为底部的单独语句:while(charRepeatCount-- &gt; 0)。如果您使用slide operator:while (charRepeatCount --&gt; 0) 写这篇文章,我会扬起眉毛,但如果您使用slide operator 写这篇文章,请给您一两点幽默和个性。但前提是您承诺不在生产环境中使用它。

祝你面试顺利!

【讨论】:

  • 感谢您抽出宝贵时间对我的代码提供宝贵的反馈。对像我这样的中级开发人员非常有用。
  • “当我采访开发人员时,我正在寻找能够告诉我 SHE 如何解决问题的信号” - 你采访过男性开发人员吗? :)
  • +1,非常有用的答案。爱它!听到篱笆另一边的人的来信总是好的。这是非常好的和有价值的建议。我将把它存储起来以备将来参考;)
  • @kotlomoy 您会注意到我在示例中同时使用了“he”和“she”。不幸的是,我采访的男性开发人员仍然远远多于女性开发人员,因为 STEM 职业仍然存在巨大差异。在将近 2 年的时间里,我注意到两性之间的能力完全没有一致的差异。
【解决方案3】:

我认为您的代码对于这项任务来说太复杂了。这是我的方法(使用 C):

#include <ctype.h>
#include <stdio.h>

void format_str(char *target, char *source) {
    int count;
    char last;
    while (*source != '\0') {
        *target = *source;
        last = *target;
        target++;
        source++;
        for (count = 1; *source == last; source++, count++)
            ; /* Intentionally left blank */
        if (count > 1)
            target += sprintf(target, "%d", count);
    }
    *target = '\0';
}

void convert_back(char *target, char *source) {
    char last;
    int val;
    while (*source != '\0') {
        if (!isdigit((unsigned char) *source)) {
            last = *source;
            *target = last;
            target++;
            source++;
        }
        else {
            for (val = 0; isdigit((unsigned char) *source); val = val*10 + *source - '0', source++)
                ; /* Intentionally left blank */
            while (--val) {
                *target = last;
                target++;
            }
        }
    }
    *target = '\0';
}

format_str 压缩字符串,convert_back 解压缩。

【讨论】:

  • 感谢另一个更简单的解决方案。
  • 我有一点疑问。在 format_str 中,在 for 循环中,您正在递增源指针而不检查结束 ('\0')。这里真的不需要吗?
  • @Prabu:它恰好在这种情况下工作,因为*source == last 将在*source == '\0' 时为假。
  • 完全正确:由于while 循环条件,您可以保证last 永远不会是'\0'。如果source 达到'\0',则*source == last 的计算结果为假,两个循环(for 和while)都停止。
  • @Prabu 请注意,在我的 C 实现中,我不检查 inside 循环。这不是问题,因为while (*++s == current) 会注意不超出范围。并且比较/访问 NUL 终止符很好。它是字符串的一部分。但是,在 C++ 实现中,我必须使用 (++it != input.end() &amp;&amp; *it == current),因为取消引用结束迭代器是未定义的行为。
【解决方案4】:

您的代码“有效”,但它不符合 C++ 中使用的一些常见模式。你应该有:

  • 使用std::string 而不是普通的char* array(s)
  • 将该字符串作为const reference 传递以避免修改,因为您将结果写入其他地方;
  • 使用 C++11 功能,例如基于范围的 for 循环和 lambda。

我认为面试官的目的是测试你处理 C++11 标准的能力,因为算法本身非常简单。

【讨论】:

  • 会试试这个,让你知道。
  • 在采访中,这正是我所寻找的。特别是对于初级开发者;我们要求您编写的这些算法非常简单,您可以在一小时内完成多个版本,并在迭代之间讨论您做了什么以及为什么。
  • -1 OP 说:“我可以随意使用 C 或 C++。”所以“我认为面试官的目的是测试你处理 C++11 标准的能力”是错误的
  • @kotlomoy:你太从字面上理解了。如果答案是在 C++ 中,那么您要检查它是否符合 C++ 风格和习语。如果答案是 C,那么您想使用 C 风格和习语。无论哪种方式,面试官都会检查候选人是否知道如何正确使用语言(这包括标准的使用方式)。
  • @LokiAstari “如果答案是 C,那么您想使用 C 风格和习语。” - 确切地。 OP 的答案是用 C 语言,所以回答“你的代码“有效”,但它不符合 C++ 中使用的一些常见模式”是不相关的。此外,关于面试官目的的假设是完全错误的。因此投反对票。
【解决方案5】:

也许面试官想测试您对现有标准库工具的了解。以下是我在 C++ 中的看法:

#include <string>
#include <sstream>
#include <algorithm>
#include <iostream>

typedef std::string::const_iterator Iter;

std::string foo(Iter first, Iter last)
{
    Iter it = first;
    std::ostringstream result;
    while (it != last) {
        it = std::find_if(it, last, [=](char c){ return c != *it; });
        result << *first << (it - first);
        first = it;
    }
    return result.str();    
}

int main()
{
    std::string s = "aaabbbbbbccddde";
    std::cout << foo(s.begin(), s.end());
}

空输入需要额外检查。

【讨论】:

    【解决方案6】:

    试试这个

    std::string str="aabbbccccddddd";
    
    for(int i=0;i<255;i++)
    {
        int c=0;
        for(int j=0;j<str.length();j++)
        {
            if(str[j] == i)
                c++;
        }
        if(c>0)
        printf("%c%d",i,c);
    }
    

    【讨论】:

    • 显然,这不是 OP 需要的
    【解决方案7】:

    我的幼稚做法:

    void pack( char const * SrcStr, char * DstBuf ) {
    
        char const * Src_Ptr = SrcStr;
        char * Dst_Ptr = DstBuf;
    
        char c = 0;
        int RepeatCount = 1;
    
        while( '\0' != *Src_Ptr ) {
    
            c = *Dst_Ptr = *Src_Ptr;
            ++Src_Ptr; ++Dst_Ptr;
    
            for( RepeatCount = 1; *Src_Ptr == c; ++RepeatCount ) {
                ++Src_Ptr;
            }
    
            if( RepeatCount > 1 ) {
                Dst_Ptr += sprintf( Dst_Ptr, "%i", RepeatCount );
                RepeatCount = 1;
            }
        }
    
        *Dst_Ptr = '\0';
    };
    
    void unpack( char const * SrcStr, char * DstBuf ) {
    
        char const * Src_Ptr = SrcStr;
        char * Dst_Ptr = DstBuf;
    
        char c = 0;
    
        while( '\0' != *Src_Ptr ) {
    
            if( !isdigit( *Src_Ptr ) ) {
                c = *Dst_Ptr = *Src_Ptr;
                ++Src_Ptr; ++Dst_Ptr;
    
            } else {
                int repeat_count = strtol( Src_Ptr, (char**)&Src_Ptr, 10 );
                memset( Dst_Ptr, c, repeat_count - 1 );
                Dst_Ptr += repeat_count - 1;
            }
        }
    
        *Dst_Ptr = '\0';
    };
    

    但是,如果面试官要求错误处理,那么解决方案就会变得更加复杂(而且丑陋)。我的便携方法:

    #include <stdlib.h>
    #include <string.h>
    #include <stdio.h>
    #include <ctype.h>
    
    // for MSVC
    #ifdef _WIN32
        #define snprintf sprintf_s
    #endif
    
    int pack( char const * SrcStr, char * DstBuf, size_t DstBuf_Size ) {
    
        int Err = 0;
    
        char const * Src_Ptr = SrcStr;
        char * Dst_Ptr = DstBuf;
    
        size_t SrcBuf_Size = strlen( SrcStr ) + 1;
        char const * SrcBuf_End = SrcStr + SrcBuf_Size;
        char const * DstBuf_End = DstBuf + DstBuf_Size;
    
        char c = 0;
        int RepeatCount = 1;
    
        // don't forget about buffers intercrossing
        if( !SrcStr || !DstBuf || 0 == DstBuf_Size \
            || (DstBuf < SrcBuf_End && DstBuf_End > SrcStr) ) {
    
            return 1;
        }
    
        // source string must contain no digits
        // check for destination buffer overflow
        while( '\0' != *Src_Ptr && Dst_Ptr < DstBuf_End - 1 \
            && !isdigit( *Src_Ptr ) && !Err ) {
    
            c = *Dst_Ptr = *Src_Ptr;
            ++Src_Ptr; ++Dst_Ptr;
    
            for( RepeatCount = 1; *Src_Ptr == c; ++RepeatCount ) {
                ++Src_Ptr;
            }
    
            if( RepeatCount > 1 ) {
                int res = snprintf( Dst_Ptr, DstBuf_End - Dst_Ptr - 1, "%i" \
                    , RepeatCount );
                if( res < 0 ) {
                    Err = 1;
                } else {
                    Dst_Ptr += res;
                    RepeatCount = 1;
                }
           }
        }
    
        *Dst_Ptr = '\0';
    
        return Err;
    };
    
    int unpack( char const * SrcStr, char * DstBuf, size_t DstBuf_Size ) {
    
        int Err = 0;
    
        char const * Src_Ptr = SrcStr;
        char * Dst_Ptr = DstBuf;
    
        size_t SrcBuf_Size = strlen( SrcStr ) + 1;
        char const * SrcBuf_End = SrcStr + SrcBuf_Size;
        char const * DstBuf_End = DstBuf + DstBuf_Size;
    
        char c = 0;
    
        // don't forget about buffers intercrossing
        // first character of source string must be non-digit
        if( !SrcStr || !DstBuf || 0 == DstBuf_Size \
            || (DstBuf < SrcBuf_End && DstBuf_End > SrcStr) || isdigit( SrcStr[0] ) ) {
    
            return 1;
        }
    
        // check for destination buffer overflow
        while( '\0' != *Src_Ptr && Dst_Ptr < DstBuf_End - 1 && !Err ) {
    
            if( !isdigit( *Src_Ptr ) ) {
                c = *Dst_Ptr = *Src_Ptr;
                ++Src_Ptr; ++Dst_Ptr;
    
            } else {
                int repeat_count = strtol( Src_Ptr, (char**)&Src_Ptr, 10 );
                if( !repeat_count || repeat_count - 1 > DstBuf_End - Dst_Ptr - 1 ) { 
                    Err = 1;
                } else {
                    memset( Dst_Ptr, c, repeat_count - 1 );
                    Dst_Ptr += repeat_count - 1;
                }
            }
        }
    
        *Dst_Ptr = '\0';
    
        return Err;
    };
    
    int main() {
    
        char str[] = "aabbbccccddddd";
        char buf1[128] = {0};
        char buf2[128] = {0};
    
        pack( str, buf1, 128 );
        printf( "pack: %s -> %s\n", str, buf1 );
    
        unpack( buf1, buf2, 128 );
        printf( "unpack: %s -> %s\n", buf1, buf2 );
    
        return 0;
    }
    

    测试:http://ideone.com/Y7FNE3。也适用于 MSVC。

    【讨论】:

      【解决方案8】:

      尽量少写样板:

      #include <iostream>
      #include <iterator>
      #include <sstream>
      using namespace std;
      
      template<typename in_iter,class ostream>
      void torle(in_iter i, ostream &&o)
      {
              while (char c = *i++) {
                      size_t n = 1;
                      while ( *i == c )
                              ++n, ++i;
                      o<<c<<n;
              }
      }
      
      template<class istream, typename out_iter>
      void fromrle(istream &&i, out_iter o)
      {
              char c; size_t n;
              while (i>>c>>n)
                      while (n--) *o++=c;
      }
      
      int main()
      {
          typedef ostream_iterator<char> to;
          string line; stringstream converted;
          while (getline(cin,line)) {
              torle(begin(line),converted);
              cout<<converted.str()<<'\n';
              fromrle(converted,ostream_iterator<char>(cout));
              cout<<'\n';
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-05-09
        • 2016-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-18
        • 1970-01-01
        • 2014-11-02
        相关资源
        最近更新 更多