LeetCode Contest 241 Question 2: Minimum Number of Swaps to Make the Binary String Alternating

preview_player
Показать описание

Рекомендации по теме
Комментарии
Автор

What is the software you are using, for white board?

lokeshchennamchetty
Автор

public:
int minSwaps(string s) {
int ans = 0, n = s.length();
int count1 = count(s.begin(), s.end(), '1');
int count0 = count(s.begin(), s.end(), '0');
if(abs(count1-count0) > 1) return -1;
if(count1 > count0){
string start1 = "";
for(int i = 0; i<n; i++){
if(i&1) start1 = start1 + '0';
else start1 = start1 + '1';
}
for(int i = 0; i<n; i++){
if(start1[i] != s[i]) ans++;
}
}
else if(count0 > count1){
string start0 = "";
for(int i = 0; i<n; i++){
if(i&1) start0 =start0 + '1';
else start0 = start0 + '0';
}
for(int i = 0; i<n; i++){
if(start0[i] != s[i]) ans++;
}
}
else if(count0 == count1){
int c0 = 0, c1 = 0;
string start0 = "";
for(int i = 0; i<n; i++){
if(i&1) start0 = start0 + '1';
else start0 = start0 + '0';
}
string start1 = "";
for(int i = 0; i<n; i++){
if(i&1) start1 = start1 + '0';
else start1 = start1 + '1';
}
for(int i = 0; i<n; i++){
if(start1[i] != s[i]) c1++;
if(start0[i] != s[i]) c0++;
}
ans = min(c0, c1);
}
return ans/2;
}
};
My code is bit lengthy any suggestion to reduce it.

keshavgupta
Автор

Explanation is not proper.I think you know how to solve that question but not able explaning it.

technologicalvivek
visit shbcf.ru