String s="101010101010";
String sub=""; //substring
int k=2;
package coreJava;
import java.util.Scanner;
public class substring {
public static void main(String args[])
{
String string, sub;
int k, c, i;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to print it's all substrings");
string = in.nextLine();
i = string.length();
System.out.println("Substrings of \""+string+"\" are :-");
for( c = 0 ; c < i ; c++ )
{
for( k = 1 ; k <= i - c ; k++ )
{
sub = string.substring(c, c+k);
System.out.println(sub);
}
}
}
}
- 取一个二进制字符串 s="1010011010";//等等
- 取一个变量k=2;
- 取另一个变量i;//这是子串的长度(i>k)
现在我想找到上面字符串的子字符串,这样如果k=2,子字符串中1的数量必须是2,如果k=3,子字符串中1的数量必须是3,依此类推...
Output should be like this:
string s="1010011010"
Enter value of k=2;
Enter length of substring i=3;
substring= 101 110 101 011
最佳答案
创建一个“窗口”,其长度为您沿字符串移动的所需子字符串的长度,并维护当前窗口中 1 的数量。每次迭代时,您都会沿着一个窗口移动窗口,测试当前窗口之外的下一个字符、当前窗口中的第一个字符并相应地更新计数。在每次迭代期间,如果您的计数等于所需的长度,则打印当前窗口中的子字符串。
public class Substring {
public static void main(String[] args) {
String str = "1010011010";
int k = 2;
int i = 3;
printAllSubstrings(str, i, k);
}
private static void printAllSubstrings(String str, int substringLength, int numberOfOnes) {
// start index of the current window
int startIndex = 0;
// count of 1s in current window
int count = 0;
// count 1s in the first i characters
for (int a = 0; a < substringLength; a++) {
if (str.charAt(a) == '1') {
count++;
}
}
while (startIndex < str.length() - substringLength + 1) {
if (count == numberOfOnes) {
System.out.print(str.substring(startIndex, startIndex + substringLength));
System.out.print(" ");
}
// Test next bit, which will be inside the window next iteration
if (str.length() > startIndex + substringLength && str.charAt(startIndex + substringLength) == '1') {
count ++;
}
// Test the starting bit, which will be outside the window next iteration
if (str.charAt(startIndex) == '1') {
count --;
}
startIndex++;
}
}
}
输出:
101 011 110 101
关于java - java中如何查找二进制字符串的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18586950/