-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoffer_58
70 lines (59 loc) · 1.28 KB
/
offer_58
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//面试题58:反转字符串
//题目1:反转单词顺序
void Reverse(char* pBegin,char* pEnd)
{
if(pBegin==nullptr||pEnd==nullptr)
return;
while(pBegin<pEnd){
char temp=*pBegin;
*pBegin=*pEnd;
*pEnd=temp;
*pBegin++;
*pEnd--;
}
}
char* ReverSentence(char* pData)
{
if(pData==nullptr)
return nullptr;
char *pBegin=pData;
char *pEnd=pData;
while(*pEnd!='\0'){
pEnd++;
}
pEnd--;
Reverse(pBegin,pEnd);//翻转整个句子
pBegin=pEnd=pData;
while(*pBegin!='\0'){
if(*pBegin==' '){
pBegin++;
pEnd--;
}else if(*pEnd==' '||*pEnd=='\0'){
Reverse(pBegin,pEnd);
pBegin=++pEnd;
}else{
pEnd++;
}
}
return pData;
}
//题目2:左旋转字符串
char* LeftRoateString(char* pStr,int n)
{
if(pStr!=nullptr){
int nLength=static<int>(strlen(pStr));
if(nLength>0&&n>0&&n<nLength){
char* pFirstStart=pStr;
char* pFirstEnd=pStr+n-1;
char* pSecondStart=pStr+n;
char* pSecondEnd=pStr+nLength-1;
//翻转字符串的前面n个字符
Reverse(pFirstStart,pFirstEnd);
//翻转字符串后面的部分
Recerse(pSecondStart,pSecondEnd);
//翻转整个字符串
Reverse(pFirstStart,pSecondEnd);
}
}
return pStr;
}