3

让我用一个例子更详细地解释我的问题。

给定一个字符串:

“谐音是在几个连续单词的开头重复相同的元音”

如果我们想将第四个单词 reiteration 移动第二个单词的位置,字符串将变为:

“同音重复是几个连续单词开头的同一个元音”

给定一个C原型如下的函数:

void move(char *s, int word_begin_ind, int word_end_ind, int target_begin_ind)

如何实现这个功能来完成这项工作?

在上面的例子中,word_begin_ind = 17, word_end_ind = 27, target_begin_ind = 10

这不是功课。其实是面试题。我有一个算法。基本思想是这样的:

(1) 使用word_begin_indand复制目标词word_end_ind

(2) from target_begin_indto word_begin_ind - 1,将每个字符移动到正确的位置。例如,移动word_begin_ind-1到“word_end_ind”、word_begin_ind-2“word_end_ind-1”等等。

(3) 最后,将副本移动到正确的位置(从target_begin_ind开始)。

我希望每个人都能明白我在问什么。

您不需要使用 c 来完成这项工作。也欢迎 C++。

谁能帮我找到其他解决方案?

4

2 回答 2

8
  1. 在一个位置的开始和另一个位置的结束之间取一个范围:

    "Assonance [is the reiteration] of the same vowel sound at the beginning of several consecutive words"
    
  2. 反转这个范围:

    "Assonance [noitaretier eht si] of the same vowel sound at the beginning of several consecutive words"
    
  3. 将此范围拆分为单词和其他所有内容:

    "Assonance [noitaretier|eht si] of the same vowel sound at the beginning of several consecutive words"
    
  4. 反义词:

    "Assonance [reiteration|eht si] of the same vowel sound at the beginning of several consecutive words"
    
  5. 反转一切-其他:

    "Assonance [reiteration|is the] of the same vowel sound at the beginning of several consecutive words"
    
  6. 所以你已经完成了。

于 2013-03-04T23:06:16.140 回答
0

我会这样解决它:

char * temp = malloc(end-begin);
memcpy(temp,s,end-begin);

现在我们知道在目标位置必须留出一些空间来放回单词,所以我想从目标位置前后移动 n 个字节,具体取决于原始单词是在目标位置之前还是之后,这应该用memmove完成,然后只需memcpy目标位置的单词

于 2013-03-04T23:19:09.990 回答