Share 859. buddy strings c++,

#buddy String, #C ++, #Coding, #Programming ** 859.Chuỗi bạn thân trong c ++ **

Chuỗi bạn thân là một chuỗi có thể được hình thành bằng cách hoán đổi hai ký tự của cùng một chuỗi.Ví dụ, các chuỗi "ABC" và "BCA" là các chuỗi bạn thân, cũng như các chuỗi "ABBA" và "BAAB".

Cho một chuỗi, s, tìm độ dài của chuỗi bạn thân dài nhất có thể được hình thành từ s.

**Ví dụ 1:**

`` `
Đầu vào: S = "AB"
Đầu ra: 2
Giải thích: Chuỗi bạn thân dài nhất là "AB".
`` `

** Ví dụ 2: **

`` `
Đầu vào: S = "AA"
Đầu ra: 2
Giải thích: Chuỗi bạn thân dài nhất là "AA".
`` `

** Ví dụ 3: **

`` `
Đầu vào: S = "ABC"
Đầu ra: 3
Giải thích: Chuỗi bạn thân dài nhất là "CBA".
`` `

**Giải pháp:**

`` `C ++
#include <Istream>
#include <String>

sử dụng không gian tên STD;

int main () {
dây;
cin >> s;

int n = s.length ();
int ans = 0;

for (int i = 0; i <n; i ++) {
for (int j = i+1; j <n; j ++) {
if (s == s [j] && i! = j) {
int k = j + 1;
while (k <n && s [k] == s ) {
K ++;
}

int l = j - 1;
while (l> = 0 && s [l] == s ) {
l--;
}

if (k - l + 1> ans) {
ANS = K - L + 1;
}
}
}
}

cout << ans << endl;

trả lại 0;
}
`` `

** Hashtags: **

* #buddy chuỗi
* #C ++
* #mã hóa
* #Programming
=======================================
#buddy strings, #C++, #Coding, #Programming **859. Buddy Strings in C++**

A buddy string is a string that can be formed by swapping two characters of the same string. For example, the strings "abc" and "bca" are buddy strings, as are the strings "abba" and "baab".

Given a string, s, find the length of the longest buddy string that can be formed from s.

**Example 1:**

```
Input: s = "ab"
Output: 2
Explanation: The longest buddy string is "ab".
```

**Example 2:**

```
Input: s = "aa"
Output: 2
Explanation: The longest buddy string is "aa".
```

**Example 3:**

```
Input: s = "abc"
Output: 3
Explanation: The longest buddy string is "cba".
```

**Solution:**

```c++
#include <iostream>
#include <string>

using namespace std;

int main() {
string s;
cin >> s;

int n = s.length();
int ans = 0;

for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (s == s[j] && i != j) {
int k = j + 1;
while (k < n && s[k] == s) {
k++;
}

int l = j - 1;
while (l >= 0 && s[l] == s) {
l--;
}

if (k - l + 1 > ans) {
ans = k - l + 1;
}
}
}
}

cout << ans << endl;

return 0;
}
```

**Hashtags:**

* #buddy strings
* #C++
* #Coding
* #Programming
 
Join Telegram ToolsKiemTrieuDoGroup
Back
Top