判断字符串的两半是否相似【LC1704】
You are given a string
sof even length. Split this string into two halves of equal lengths, and letabe the first half andbbe the second half.Two strings are alike if they have the same number of vowels (
'a','e','i','o','u','A','E','I','O','U'). Notice thatscontains uppercase and lowercase letters.Return
trueifaandbare alike. Otherwise, returnfalse.
给你一个偶数长度的字符串
s。将其拆分成长度相同的两半,前一半为a,后一半为b。两个字符串 相似 的前提是它们都含有相同数目的元音(
'a','e','i','o','u','A','E','I','O','U')。注意,s可能同时含有大写和小写字母。如果
a和b相似,返回true;否则,返回false。
1111 怎么在草稿里没有发出去 泪目
-
思路:使用双指针统计字符串a和字符串b中元音字母的个数,个数相同则返回true
-
实现
class Solution { public boolean halvesAreAlike(String s) { int left = 0; int right = s.length()-1; int a = 0; int b = 0; while (left < right){ if (isVowels(s.charAt(left))){ a++; } if (isVowels(s.charAt(right))){ b++; } left++; right--; } return a == b; } public boolean isVowels(char c){ if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ){ return true; } if (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' ){ return true; } return false; } } -
复杂度
- 时间复杂度:O(n)O(n)O(n),n为两个字符串的最大长度
- 空间复杂度:O(1)O(1)O(1)

该博客介绍了一个问题,即如何判断一个偶数长度字符串的两半是否具有相同的元音数量,以此确定它们是否相似。提供的解决方案是使用双指针分别统计前后两半字符串中的元音个数,若相等则返回true,否则返回false。算法的时间复杂度为O(n),空间复杂度为O(1)。
3044

被折叠的 条评论
为什么被折叠?



