判断字符串的两半是否相似【LC1704】
You are given a string
s
of even length. Split this string into two halves of equal lengths, and leta
be the first half andb
be 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 thats
contains uppercase and lowercase letters.Return
true
ifa
andb
are 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)