leetcode 2027. Minimum Moves to Convert String（python）

2022-01-31 08:27:11

「 This is my participation 11 The fourth of the yuegengwen challenge 10 God , Check out the activity details ：2021 One last more challenge

describe

You are given a string s consisting of n characters which are either 'X' or 'O'.

A move is defined as selecting three consecutive characters of s and converting them to 'O'. Note that if a move is applied to the character 'O', it will stay the same.

Return the minimum number of moves required so that all the characters of s are converted to 'O'.

Example 1:

``````Input: s = "XXX"
Output: 1
Explanation: XXX -> OOO
We select all the 3 characters and convert them in one move.
Copy code ``````

Example 2:

``````Input: s = "XXOX"
Output: 2
Explanation: XXOX -> OOOX -> OOOO
We select the first 3 characters in the first move, and convert them to 'O'.
Then we select the last 3 characters and convert them so that the final string contains all 'O's.
Copy code ``````

Example 3:

``````Input: s = "OOOO"
Output: 0
Explanation: There are no 'X's in s to convert.
Copy code ``````

Note:

``````3 <= s.length <= 1000
s[i] is either 'X' or 'O'.
Copy code ``````

analysis

According to the meaning , Is to give only X perhaps O String s , Ask us to find the minimum number of operations , Can be s All the characters in the are changed to O character , The process of each operation is as follows ： Select three consecutive characters at a time , If the character is X Turn to O , If the character is O Is the same .

Although the problem seems a little confusing , But in fact, it's still very simple after you figure it out , The idea is as follows ：

• Initialize a result result by 0 , Indexes i by 0
• When i<len(s) When , If s[i] by O , No conversion operation is required , direct i Add one to judge the next character , Otherwise, when s[i] by X When , No matter X What are the next two characters , There must be an operation , Change all three characters into O , then i Add three to judge the next character
• Return after loop result

``````class Solution(object):
def minimumMoves(self, s):
"""
:type s: str
:rtype: int
"""
result = 0
i = 0
while i<len(s):
if s[i]=='O':
i += 1
continue
else:
result += 1
i += 3
return result

Copy code ``````

Running results

``````Runtime: 16 ms, faster than 93.99% of Python online submissions for Minimum Moves to Convert String.
Memory Usage: 13.3 MB, less than 99.05% of Python online submissions for Minimum Moves to Convert String.
Copy code ``````