日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

leetcode A String Replacement Problem---流程图

發布時間:2025/6/15 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode A String Replacement Problem---流程图 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Replace all occurrence of the given pattern to ‘X’.
For example, given that the pattern=”abc”, replace “abcdeffdfegabcabc” with “XdeffdfegX”. Note that multiple occurrences of abc’s that are contiguous will be replaced with only one ‘X’.


First, it is not clear whether the problem mentions an in-place replacement or not, so be sure to ask this question during an interview. Many interview questions asked are purposely ambiguous. It is expected that the candidate ask thought-provoking questions of the interviewer in order to better answer the question. Here, we will assume that it is an in-place replacement.


思路:
1、還是用一前一后的兩個指針,前一個指針用于遍歷,后一個指針用于修改值。
2、如果pFast當前所指的位置可以匹配,pFast向前移動Pattern長度,并且記下匹配的信息,直到找到第一個不能匹配的點。
3、如果標記顯示有子串匹配。則將pSlow替換為指定的字符。
4、如果pFast還沒有到Str的尾部,則將pFast賦給pSlow,因為pFast是剛剛找到的第一個未匹配的點。
?流程圖




bool IsMatch(const char *Str, const char *Pattern) { assert(Str && Pattern); while(*Pattern) { if(*Str++ != *Pattern++) { return false; } } return true; } void StrReplace(char *Str, const char *Pattern, const char ReplaceChar) { assert(Str && Pattern); int nLen = strlen(Pattern); if(nLen <= 0) { return; } char *pSlow, *pFast; pSlow = pFast = Str; bool isMatch = false; while(*pFast != '\0') { isMatch = false; while(IsMatch(pFast, Pattern))//略過與模式串匹配的部分,定位第一個不匹配的字符 { isMatch = true; pFast += nLen; } if(isMatch)//如果有匹配的,替換成相應字符 { *pSlow++ = ReplaceChar; } if(*pFast != '\0')//如果pFast沒有指向末尾 { *pSlow++ = *pFast++; //等同于*(pSlow++) = *(pFast++);因為++的優先級高于* } } *pSlow = '\0';//加上結束標志 }

測試代碼

#include<stdio.h> #include<assert.h> #include<string.h> int main() { const int MAX_N = 50; char Pattern[MAX_N]; char Str[MAX_N]; while(gets(Str) && gets(Pattern)) { StrReplace(Str, Pattern, 'X'); puts(Str); } return 1;



總結

以上是生活随笔為你收集整理的leetcode A String Replacement Problem---流程图的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。