字符串的旋转

题目描述

对于一个字符串,和字符串中的某一位置,请设计一个算法,将包括i位置在内的左侧部分移动到右边,将右侧部分移动到左边。

给定字符串A和它的长度n以及特定位置p,请返回旋转后的结果。

测试样例:
"ABCDEFGH",8,4
返回:"FGHABCDE"

简单题

# -*- coding:utf-8 -*-

class StringRotation:
    def rotateString(self, A, n, p):
        # write code here
        return A[p + 1:] + A[: p + 1]

if __name__ == "__main__":
	a = StringRotation()
	print a.rotateString("ABCDEFGH",8,4)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现字符串旋转操作,可以使用函数指针来完成。首先,你需要定义一个函数指针类型,用于指向字符串旋转操作的函数。然后,你可以创建一个函数,该函数接受一个字符串旋转次数作为参数,并调用函数指针执行字符串旋转操作。以下是一个示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> typedef void (*RotateStringFuncPtr)(char*, int); void rotateLeft(char* str, int rotateCount) { int length = strlen(str); rotateCount %= length; // 创建一个临时缓冲区,用于保存旋转后的字符串 char* temp = (char*)malloc((length + 1) * sizeof(char)); strcpy(temp, str); // 将字符串中的字符向左旋转 for (int i = 0; i < length; i++) { str[i] = temp[(i + rotateCount) % length]; } free(temp); } void rotateRight(char* str, int rotateCount) { int length = strlen(str); rotateCount %= length; // 创建一个临时缓冲区,用于保存旋转后的字符串 char* temp = (char*)malloc((length + 1) * sizeof(char)); strcpy(temp, str); // 将字符串中的字符向右旋转 for (int i = 0; i < length; i++) { str[i] = temp[(i - rotateCount + length) % length]; } free(temp); } int main() { char str[] = "Hello, World!"; int rotateCount = 2; RotateStringFuncPtr rotateFunc = rotateLeft; rotateFunc(str, rotateCount); printf("Rotated string: %s\n", str); return 0; } ``` 在上面的示例代码中,我们定义了两个函数 `rotateLeft` 和 `rotateRight`,分别实现左旋转和右旋转操作。然后,我们定义了一个函数指针类型 `RotateStringFuncPtr`,用于指向字符串旋转操作的函数。在 `main` 函数中,我们创建了一个函数指针 `rotateFunc`,并将其指向 `rotateLeft` 函数。最后,我们调用 `rotateFunc` 函数指针执行字符串旋转操作,并打印旋转后的字符串。 请注意,这只是一个示例代码,你可以根据实际需求进行修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值