aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2024-06-30 12:38:46 -0600
committerJack Sangdahl <[email protected]>2024-06-30 12:38:46 -0600
commit000ebc1d1cfeb1adfcd2c55ced5dc8c33ad7cdb8 (patch)
tree275a893957bab764faeaa48feb4a7553fabfdc62
parent0cea53b366c1ef1b94693772b8f3c3299fcd699b (diff)
downloadleetcode-000ebc1d1cfeb1adfcd2c55ced5dc8c33ad7cdb8.tar.gz
leetcode-000ebc1d1cfeb1adfcd2c55ced5dc8c33ad7cdb8.zip
2262. total appeal of a string
-rw-r--r--total_appeal_string.c28
-rw-r--r--total_appeal_string.py28
2 files changed, 56 insertions, 0 deletions
diff --git a/total_appeal_string.c b/total_appeal_string.c
new file mode 100644
index 0000000..8c5938c
--- /dev/null
+++ b/total_appeal_string.c
@@ -0,0 +1,28 @@
+// 2262. Total Appeal of A String
+#include "leetcode.h"
+
+/*
+ * the appeal of a string is the number of distinct characters found in the
+ * string. for example, the appeal of "aabca" is 3 because it has 3 distinct
+ * characters 'a', 'b' and 'c'. given a string 's', return the total appeal of
+ * along long its substrings. a substring is a contiguous sequence of characters
+ * within a string.
+ */
+
+long long appealSum(char *s) {
+ long long ans = 0;
+ int n = strlen(s);
+ int *dp = (int *)calloc(26, sizeof(int));
+ for (int i = 0; i < n; i++) {
+ ans += (long long)(i + 1 - dp[s[i] - 'a']) * (long long)(n - i);
+ dp[s[i] - 'a'] = i + 1;
+ }
+ free(dp);
+ return ans;
+}
+
+int main() {
+ char *s1 = "aabca", *s2 = "code";
+ printf("%lld\n", appealSum(s1)); // expect: 28
+ printf("%lld\n", appealSum(s2)); // expect: 20
+}
diff --git a/total_appeal_string.py b/total_appeal_string.py
new file mode 100644
index 0000000..1ec7ae8
--- /dev/null
+++ b/total_appeal_string.py
@@ -0,0 +1,28 @@
+# 2262. Total Appeal of A String
+
+"""
+the appeal of a string is the number of distinct characters found in the
+string. for example, the appeal of "aabca" is 3 because it has 3 distinct
+characters 'a', 'b' and 'c'. given a string 's', return the total appeal of
+along long its substrings. a substring is a contiguous sequence of characters
+within a string.
+"""
+
+
+class Solution(object):
+ def appealSum(self, s):
+ """
+ :type s: str
+ :rtype: int
+ """
+ ans, last = 0, {}
+ for i, c in enumerate(s):
+ last[c] = i + 1
+ ans += sum(last.values())
+ return ans
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.appealSum("abbca")) # expect: 28
+ print(obj.appealSum("code")) # expect: 20