LeetCode 1332 : palindromic subsequence [解決]を削除する
難易度:簡単
ジャンプします
問題声明
Given a string s
consisting only of letters 'a'
and 'b'
. In a single step you can remove one palindromic subsequence from s
.
Return the minimum number of steps to make the given string empty.
A string is a subsequence of a given string, if it is generated by deleting some characters of a given string without changing its order.
A string is called palindrome if is one that reads the same backward as well as forward.
Example 1:
Input: s = "ababa"
Output: 1
Explanation: String is already palindrome
Example 2:
Input: s = "abb"
Output: 2
Explanation: "abb" -> "bb" -> "".
Remove palindromic subsequence "a" then "bb".
Example 3:
Input: s = "baabb"
Output: 2
Explanation: "baabb" -> "b" -> "".
Remove palindromic subsequence "baab" then "b".
Example 4:
Input: s = ""
Output: 0
Constraints:
-
0 <= s.length <= 1000
-
s
only consists of letters 'a' and 'b'
解説
Did you get the question? If yes, then you are a PRO, if not then don't worry, you are normal, like me. So before understanding the question, let's first understand what are subsequence and palindrome.
shivam
, ham
削除後の文字列s
, i
and v
. 部分文字列:substring . 部分文字列は文字列内の連続した文字列です.文字列用
shivam
, iva
部分文字列ですham
がない.それで、「すべての部分文字列は副配列でもありますが、逆も同様です.」パラリンドロームpalindrome は、単語、数字、句、または他のシーケンスの文字である.
madam
or racecar
. 解決に行く前に、いくつかのヒントを見たいですか?こちらは
解決策
We are going to use the below ideas to solve this question:
- If any string is empty, then we don't need to do anything and return
0
. - If a string is a palindrome then we can delete the whole string in a single operation as a string is also a subsequence of itself. For such case, we need to return
1
. - A string of any length consists of a single type of character is always a subsequence eg.
aaaaa
,bbb
,a
etc. - So, I can delete a subsequence containing all characters of the same type from the string. eg. from string
aaabbbababa
I can removeaaaaaa
as it's a subsequence and palindrome as well. - And surprise, we are left with the string
bbbbb
which is also a palindrome so we can delete this in a single operation. - As the string can contain only
'a'
or'b'
only. So if the string is not palindrome then I can delete all the'a'
s in the first pass then all the'b'
s in the second pass, so the max operations we need is2
if the string is not a palindrome.
実装
C++ Code:
class Solution {
public:
int removePalindromeSub(string s) {
// Check if string is empty
if(s.empty())
return 0;
int len=s.size();
// Check for pallindrome
for(int i=0; i<=len/2; i++){
// If not pallindrome then 2 operations are needed
if(s[i] != s[len-i-1])
return 2;
}
// If pallindrome then only one operation is needed
return 1;
}
};
Runnable C++ Code:
Reference
この問題について(LeetCode 1332 : palindromic subsequence [解決]を削除する), 我々は、より多くの情報をここで見つけました https://dev.to/shivams136/leetcode-1332-remove-palindromic-subsequences-6ddテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol