Skip to content

feat: add solutions to lc problem: No.3556 #4430

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 162 additions & 4 deletions solution/3500-3599/3556.Sum of Largest Prime Substrings/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,32 +71,190 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/3500-3599/3556.Su

<!-- solution:start -->

### 方法一
### 方法一:枚举 + 哈希表

我们可以枚举所有的子字符串,然后判断它们是否是质数。由于题目要求我们返回最大的 3 个不同质数的和,因此我们可以使用一个哈希表来存储所有的质数。

在遍历完所有的子字符串后,我们将哈希表中的质数按从小到大的顺序排序,然后取出最大的 3 个质数进行求和。

如果哈希表中质数的数量小于 3,则返回所有质数的和。

时间复杂度 $O(n^2 \times \sqrt{M})$,空间复杂度 $O(n^2)$,其中 $n$ 为字符串的长度,而 $M$ 为字符串中最大的子字符串的值。

<!-- tabs:start -->

#### Python3

```python

class Solution:
def sumOfLargestPrimes(self, s: str) -> int:
def is_prime(x: int) -> bool:
if x < 2:
return False
return all(x % i for i in range(2, int(sqrt(x)) + 1))

st = set()
n = len(s)
for i in range(n):
x = 0
for j in range(i, n):
x = x * 10 + int(s[j])
if is_prime(x):
st.add(x)
return sum(sorted(st)[-3:])
```

#### Java

```java

class Solution {
public long sumOfLargestPrimes(String s) {
Set<Long> st = new HashSet<>();
int n = s.length();

for (int i = 0; i < n; i++) {
long x = 0;
for (int j = i; j < n; j++) {
x = x * 10 + (s.charAt(j) - '0');
if (is_prime(x)) {
st.add(x);
}
}
}

List<Long> sorted = new ArrayList<>(st);
Collections.sort(sorted);

long ans = 0;
int start = Math.max(0, sorted.size() - 3);
for (int idx = start; idx < sorted.size(); idx++) {
ans += sorted.get(idx);
}
return ans;
}

private boolean is_prime(long x) {
if (x < 2) return false;
for (long i = 2; i * i <= x; i++) {
if (x % i == 0) return false;
}
return true;
}
}
```

#### C++

```cpp

class Solution {
public:
long long sumOfLargestPrimes(string s) {
unordered_set<long long> st;
int n = s.size();

for (int i = 0; i < n; ++i) {
long long x = 0;
for (int j = i; j < n; ++j) {
x = x * 10 + (s[j] - '0');
if (is_prime(x)) {
st.insert(x);
}
}
}

vector<long long> sorted(st.begin(), st.end());
sort(sorted.begin(), sorted.end());

long long ans = 0;
int cnt = 0;
for (int i = (int) sorted.size() - 1; i >= 0 && cnt < 3; --i, ++cnt) {
ans += sorted[i];
}
return ans;
}

private:
bool is_prime(long long x) {
if (x < 2) return false;
for (long long i = 2; i * i <= x; ++i) {
if (x % i == 0) return false;
}
return true;
}
};
```

#### Go

```go
func sumOfLargestPrimes(s string) (ans int64) {
st := make(map[int64]struct{})
n := len(s)

for i := 0; i < n; i++ {
var x int64 = 0
for j := i; j < n; j++ {
x = x*10 + int64(s[j]-'0')
if isPrime(x) {
st[x] = struct{}{}
}
}
}

nums := make([]int64, 0, len(st))
for num := range st {
nums = append(nums, num)
}
sort.Slice(nums, func(i, j int) bool { return nums[i] < nums[j] })
for i := len(nums) - 1; i >= 0 && len(nums)-i <= 3; i-- {
ans += nums[i]
}
return
}

func isPrime(x int64) bool {
if x < 2 {
return false
}
sqrtX := int64(math.Sqrt(float64(x)))
for i := int64(2); i <= sqrtX; i++ {
if x%i == 0 {
return false
}
}
return true
}
```

#### TypeScript

```ts
function sumOfLargestPrimes(s: string): number {
const st = new Set<number>();
const n = s.length;

for (let i = 0; i < n; i++) {
let x = 0;
for (let j = i; j < n; j++) {
x = x * 10 + Number(s[j]);
if (isPrime(x)) {
st.add(x);
}
}
}

const sorted = Array.from(st).sort((a, b) => a - b);
const topThree = sorted.slice(-3);
return topThree.reduce((sum, val) => sum + val, 0);
}

function isPrime(x: number): boolean {
if (x < 2) return false;
for (let i = 2; i * i <= x; i++) {
if (x % i === 0) return false;
}
return true;
}
```

<!-- tabs:end -->
Expand Down
166 changes: 162 additions & 4 deletions solution/3500-3599/3556.Sum of Largest Prime Substrings/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,32 +69,190 @@ edit_url: https://github.com/doocs/leetcode/edit/main/solution/3500-3599/3556.Su

<!-- solution:start -->

### Solution 1
### Solution 1: Enumeration + Hash Table

We can enumerate all substrings and check whether they are prime numbers. Since the problem requires us to return the sum of the largest 3 distinct primes, we can use a hash table to store all the primes.

After traversing all substrings, we sort the primes in the hash table in ascending order, and then take the largest 3 primes to calculate the sum.

If there are fewer than 3 primes in the hash table, return the sum of all primes.

The time complexity is $O(n^2 \times \sqrt{M})$, and the space complexity is $O(n^2)$, where $n$ is the length of the string and $M$ is the value of the largest substring.

<!-- tabs:start -->

#### Python3

```python

class Solution:
def sumOfLargestPrimes(self, s: str) -> int:
def is_prime(x: int) -> bool:
if x < 2:
return False
return all(x % i for i in range(2, int(sqrt(x)) + 1))

st = set()
n = len(s)
for i in range(n):
x = 0
for j in range(i, n):
x = x * 10 + int(s[j])
if is_prime(x):
st.add(x)
return sum(sorted(st)[-3:])
```

#### Java

```java

class Solution {
public long sumOfLargestPrimes(String s) {
Set<Long> st = new HashSet<>();
int n = s.length();

for (int i = 0; i < n; i++) {
long x = 0;
for (int j = i; j < n; j++) {
x = x * 10 + (s.charAt(j) - '0');
if (is_prime(x)) {
st.add(x);
}
}
}

List<Long> sorted = new ArrayList<>(st);
Collections.sort(sorted);

long ans = 0;
int start = Math.max(0, sorted.size() - 3);
for (int idx = start; idx < sorted.size(); idx++) {
ans += sorted.get(idx);
}
return ans;
}

private boolean is_prime(long x) {
if (x < 2) return false;
for (long i = 2; i * i <= x; i++) {
if (x % i == 0) return false;
}
return true;
}
}
```

#### C++

```cpp

class Solution {
public:
long long sumOfLargestPrimes(string s) {
unordered_set<long long> st;
int n = s.size();

for (int i = 0; i < n; ++i) {
long long x = 0;
for (int j = i; j < n; ++j) {
x = x * 10 + (s[j] - '0');
if (is_prime(x)) {
st.insert(x);
}
}
}

vector<long long> sorted(st.begin(), st.end());
sort(sorted.begin(), sorted.end());

long long ans = 0;
int cnt = 0;
for (int i = (int) sorted.size() - 1; i >= 0 && cnt < 3; --i, ++cnt) {
ans += sorted[i];
}
return ans;
}

private:
bool is_prime(long long x) {
if (x < 2) return false;
for (long long i = 2; i * i <= x; ++i) {
if (x % i == 0) return false;
}
return true;
}
};
```

#### Go

```go
func sumOfLargestPrimes(s string) (ans int64) {
st := make(map[int64]struct{})
n := len(s)

for i := 0; i < n; i++ {
var x int64 = 0
for j := i; j < n; j++ {
x = x*10 + int64(s[j]-'0')
if isPrime(x) {
st[x] = struct{}{}
}
}
}

nums := make([]int64, 0, len(st))
for num := range st {
nums = append(nums, num)
}
sort.Slice(nums, func(i, j int) bool { return nums[i] < nums[j] })
for i := len(nums) - 1; i >= 0 && len(nums)-i <= 3; i-- {
ans += nums[i]
}
return
}

func isPrime(x int64) bool {
if x < 2 {
return false
}
sqrtX := int64(math.Sqrt(float64(x)))
for i := int64(2); i <= sqrtX; i++ {
if x%i == 0 {
return false
}
}
return true
}
```

#### TypeScript

```ts
function sumOfLargestPrimes(s: string): number {
const st = new Set<number>();
const n = s.length;

for (let i = 0; i < n; i++) {
let x = 0;
for (let j = i; j < n; j++) {
x = x * 10 + Number(s[j]);
if (isPrime(x)) {
st.add(x);
}
}
}

const sorted = Array.from(st).sort((a, b) => a - b);
const topThree = sorted.slice(-3);
return topThree.reduce((sum, val) => sum + val, 0);
}

function isPrime(x: number): boolean {
if (x < 2) return false;
for (let i = 2; i * i <= x; i++) {
if (x % i === 0) return false;
}
return true;
}
```

<!-- tabs:end -->
Expand Down
Loading