当前位置:网站首页>2000. reverse word prefix

2000. reverse word prefix

2022-07-23 09:12:00 Mr Gao

2000. Reverse word prefix

I'll give you a subscript from 0 Starting string word And a character ch . find ch First occurrence of subscript i , reverse word From the subscript 0 Start 、 Until the subscript i end ( Including subscript i ) That part of the character . If word There are no characters in ch , Then no operation is required .

 for example , If  word = "abcdefd"  And  ch = "d" , Then you should   reverse   From the subscript  0  Start 、 Until the subscript  3  end ( Including subscript  3 ). The result string will be  "dcbaefd" .

return Result string .

Example 1:

Input :word = “abcdefd”, ch = “d”
Output :“dcbaefd”
explain :“d” The first time it appears in the subscript 3 .
Reverse subscript 0 To the subscript 3( Including subscript 3) This character , The result string is “dcbaefd” .

Example 2:

Input :word = “xyxzxe”, ch = “z”
Output :“zxyxxe”
explain :“z” The first and only occurrence is in the subscript 3 .
Reverse subscript 0 To the subscript 3( Including subscript 3) This character , The result string is “zxyxxe” .

Example 3:

Input :word = “abcd”, ch = “z”
Output :“abcd”
explain :“z” There is no in word in .
No inversion is required , The result string is “abcd” .

The solution code is as follows :

int find_inde(char *s,char ch){
    
    int i=0;
    while(s[i]!='\0'){
    
        if(s[i]==ch){
    
            return i;
        }
        i++;
    }
    return -1;
}

void reverse(char *s,int index){
    
    int  i;
    for(i=0;i<index/2+1;i++){
    
        char t=s[index-i];
        s[index-i]=s[i];
        s[i]=t;;


    }
}
char * reversePrefix(char * word, char ch){
    
    int index=find_inde(word,ch);
    if(index!=-1){
    
        reverse(word,index);
    }
    return word;

}
原网站

版权声明
本文为[Mr Gao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207230045575401.html