当前位置:网站首页>Leetcode2027. Minimum number of operations to convert a string (yes, once)

Leetcode2027. Minimum number of operations to convert a string (yes, once)

2022-06-11 19:40:00 I'm not xiaohaiwa~~~~

 Insert picture description here
Give you a string s , from n Characters make up , Each character is not ‘X’ Namely ‘O’ .

once operation Defined as from s Selected from Three consecutive characters And convert each selected character to ‘O’ . Be careful , If the character is already ‘O’ , Just keep unchanged .

Return to s All characters in are converted to ‘O’ executable least Operating frequency .

Example 1:

 Input :s = "XXX"
 Output :1
 explain :XXX -> OOO
 One operation , Select All  3  Characters , And turn them into  'O' .

Example 2:

 Input :s = "XXOX"
 Output :2
 explain :XXOX -> OOOX -> OOOO
 The first operation , Choose the former  3  Characters , And convert these characters to  'O' .
 then , After selection  3  individual 

character , And perform the conversion . The resulting string consists entirely of characters ‘O’ form .
Example 3:

 Input :s = "OOOO"
 Output :0
 explain :s  There is no need to convert  'X' .
 

Tips :

  • 3 <= s.length <= 1000
  • s[i] by ‘X’ or ‘O’

Code:

class Solution {
    
public:
    int minimumMoves(string s) {
    
        int res=0;
        for(int i=0;i<s.length();i++)
        {
    
            if(s[i]=='X')
            {
    
                
                int cnt=0;
                if((i+1)<s.length())
                {
    
                    cnt++;
                    s[i]='O';
                }
                if((i+2)<s.length())
                {
    
                    cnt++;
                    s[i]='O';
                }
                i+=cnt;
                res++;
                
            }
        }
        return res;
        
    }
};
原网站

版权声明
本文为[I'm not xiaohaiwa~~~~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111939088079.html