ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

leetcode 耗时100 1864. Minimum Number of Swaps to Make the Binary String Alternating

leetcode 耗时100 1864. Minimum Number of Swaps to Make the Binary String Alternating Problem: 1864. 构成交替字符串需要的最小交换次数耗时100%首先若是偶数个则0和1个数相同才行若是计数个则0和1个数相差1个。然后就是只存在两种情况0开始或者1开始若这两种情况的0和1个数符合输入则只需要统计两者不相同的数字个数即可最后返回最小值/2交换两者的01即可Codeclass Solution { public: int minSwaps(string s) { int a0 0, a1 0, n s.size(); if(n 1) return 0; if(n 2) { if((s01 || s10)) return 0; } if(n3) { if((s010 || s101)) return 0; } vectorint ori, stand0(n), stand1(n); for(char c : s) { if(c0) a0; else a1; ori.push_back(c-0); } if((n1) 0 a0!a1) return -1; if((n1) 1 abs(a0 - a1)!1) return -1; stand1[0] 1; for(int i 1; i n; i) { stand0[i] (i1); stand1[i] 1 - (i1); } int s0 2000, s1 2000; if(a0 (int)ceil(n/2.0f) a1 n/2) { s0 0; for(int i 0; i n; i) { if(stand0[i] ! ori[i]) s0; } } if(a1 (int)ceil(n/2.0f) a0 n/2) { s1 0; for(int i 0; i n; i) { if(stand1[i] ! ori[i]) s1; } } if(s0 2000) return s1/2; if(s1 2000) return s0/2; return min(s0/2, s1/2); } };
返回列表