字符串反转-编辑距离-约瑟夫环的实现

A字符串反转

#include <cstdio> #include <cstdlib> #include <string> /*string reverse: input:hello world output:world hello 思想:将字符串全部反转后再以空格为标志,将局部字符串再反转 */ int main(void) { void string_reverse(char *str,int len); void word_reverse(char* str); char str[] = "hello world"; word_reverse(str); printf("%s/n",str); return 0; } void string_reverse(char *str,int len) { char *head = str; char *tail = str + len - 1; char temp; for(;head<tail;head++,tail--) { temp = *head; *head = *tail; *tail = temp; } } void word_reverse(char *str) { char *p = str; int word_len = 0; int len = strlen(str); string_reverse(str,len); printf("%s/n",str); while(*p != '/0') { word_len++; p++; if(*p == ' ' || *p == '/0') { string_reverse(p-word_len,word_len); word_len = -1;//-1是因为p指向的这个当前的空格会当做下个单词的一个字符 } } }

B计算字符串间的编辑距离。

编辑距离:给定两个字符串S1和S2,它们间的edit distace指将S1装换为S2所需的最小编辑操作次数。编辑操作指:插入一个字符、删除一个字符、替换一个字符。

#include <cstdio> #include <cstdlib> #include <string.h> #include <vector> using namespace std; int main(void) { int EditDistance(char *s1,char *s2); int minimal(int a,int b,int c); char s1[] = "cats",s2[] = "fast"; int d = EditDistance(s1,s2); printf("The edit distance between %s and %s is %d/n",s1,s2,d); return 0; } int minimal(int a,int b,int c) { int t = (a < b ? a : b); return t < c ? t : c; } int EditDistance(char *s1,char *s2) { int m = strlen(s1) ,n = strlen(s2),i,j,temp; vector<vector<int> > Array; Array.resize(m+1); for(i = 0;i <= m;i++) Array[i].resize(n+1); for(i = 0;i <= m;i++) Array[i][0] = i; for(j = 0;j <= n;j++) Array[0][j] = j; for(i = 1;i <= m;i++) for(j = 1;j <= n;j++) { temp = Array[i -1][j - 1] + (s1[i - 1] == s2[j - 1] ? 0 : 1 ); Array[i][j] = minimal(temp,Array[i-1][j] + 1,Array[i][j - 1] + 1); } return Array[m][n]; }

 C约瑟夫环的实现(修改百度知道程序)

#include<cstdio> #include<cstdlib> struct LNode { int data; LNode* link; }; typedef LNode* LinkList; void JOSEPHUS (int n, int k, int m) { LinkList p, r, list = NULL; for (int i = 0;i < n;i++) { p = (LinkList) malloc (sizeof (LNode)); p->data = i; if (list == NULL) list = p; else r->link = p; r = p; } p->link = list; p = list; for (i = 0; i < k; i++) { r = p; p = p->link; } while (p->link != p) { for (i = 0; i < m - 1; i++) { r = p; p = p->link; } r->link = p->link; printf ("%4d ", p->data); free (p); p = r->link; } printf("%4d",r->data); } int main(void) { JOSEPHUS(10,0,2); return 0; }

 

 

你可能感兴趣的:(String,list,百度,null,input,distance)