hw1 java

mail@pastecode.io avatar
unknown
java
7 months ago
2.6 kB
3
Indexable
Never
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class RegExp {

    public static void main(String[] args) {
        String str1 = args[1];
        String str2 = args[2];
        int s2Count = Integer.parseInt(args[3]);

        try {
            BufferedReader reader = new BufferedReader(new FileReader(args[0]));
            String line;
            while ((line = reader.readLine()) != null) {
                // Check if it is a palindrome
                boolean isPalindrome = isPalindrome(line);

                // Check if it contains a specific string str_1
                boolean containsStr1 = containsString(line, str1);

                // Check if it contains a specific string str_2 equal to or more than n times
                boolean containsStr2N = containsStringNTimes(line, str2, s2Count);

                // Check if it contains the string a^{m}Xb^{2m}
                boolean containsStringAB = containsStringAB(line, str1, str2);

                // Print the output in the required format
                System.out.printf("%s,%s,%s,%s\n",
                        isPalindrome ? "Y" : "N",
                        containsStr1 ? "Y" : "N",
                        containsStr2N ? "Y" : "N",
                        containsStringAB ? "Y" : "N");
            }
            reader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }public static boolean isPalindrome(String inputStr) {
        int left = 0;
        int right = inputStr.length() - 1;
        while (left < right) {
            if (inputStr.charAt(left) != inputStr.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }

    public static boolean containsString(String str, String substr) {
        return str.contains(substr);
    }

    public static boolean containsStringNTimes(String str, String substr, int n) {
        int count = 0;
        int pos = 0;
        while ((pos = str.indexOf(substr, pos)) != -1) {
            count++;
            pos += substr.length();
        }
        return count >= n;
    }

    public static boolean containsStringAB(String str, String a, String b) {
        int posA = str.indexOf(a);
        if (posA == -1) {
            return false;
        }
        int posB = str.indexOf(b + b, posA + a.length());
        if (posB == -1) {
            return false;
        }
        if (posB + 2 * b.length() < str.length() && str.charAt(posB + 2 * b.length()) == b.charAt(0)) {
            return true;
        }
        return false;
    }
}
Leave a Comment