classSolution: defisAnagram(self, s: str, t: str) -> bool: a = [0] * 26 if len(s) != len(t): returnFalse for i in s: a[ord(i) - ord('a')] += 1 for i in t: a[ord(i) - ord('a')] -= 1 for i in a: if i != 0: returnFalse returnTrue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
publicbooleanisAnagram(String s, String t){ int[] cnts = newint[26]; for (char c : s.toCharArray()) { cnts[c - 'a']++; } for (char c : t.toCharArray()) { cnts[c - 'a']--; } for (int cnt : cnts) { if (cnt != 0) { returnfalse; } } returntrue; }
classSolution: deflongestPalindrome(self, s: str) -> int: list = [0] * 100 for i in s: list[ord(i) - ord('A')] += 1 rlt = 0 for i in list: rlt += i // 2 * 2 if rlt < len(s): rlt += 1 return rlt
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicintlongestPalindrome(String s){ int[] cnts = newint[256]; for (char c : s.toCharArray()) { cnts[c]++; } int palindrome = 0; for (int cnt : cnts) { palindrome += (cnt / 2) * 2; } if (palindrome < s.length()) { palindrome++; // 这个条件下 s 中一定有单个未使用的字符存在,可以把这个字符放到回文的最中间 } return palindrome; }
classSolution: defcountSubstrings(self, s: str) -> int: rlt = 0 for i in range(len(s)): rlt += self.expandFromMid(s, i, i) # 偶数情况 for i in range(len(s)): rlt += self.expandFromMid(s, i, i + 1) #奇数情况 return rlt
defexpandFromMid(self, s: str, i: int, j: int): count = 0 while i >= 0and j < len(s) and s[i] == s[j]: i -= 1 j += 1 count += 1 return count
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
privateint cnt = 0;
publicintcountSubstrings(String s){ for (int i = 0; i < s.length(); i++) { extendSubstrings(s, i, i); // 奇数长度 extendSubstrings(s, i, i + 1); // 偶数长度 } return cnt; }
privatevoidextendSubstrings(String s, int start, int end){ while (start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)) { start--; end++; cnt++; } }
publicbooleanisPalindrome(int x){ if (x == 0) { returntrue; } if (x < 0 || x % 10 == 0) { returnfalse; } int right = 0; while (x > right) { right = right * 10 + x % 10; x /= 10; } return x == right || x == right / 10; }