Home > Mobile >  Is there any way to convert string to 2d matrix in less than or equal to O(nlgn) time?
Is there any way to convert string to 2d matrix in less than or equal to O(nlgn) time?

Time:11-21

I have an assignment about divide and conquer which isn't the problem at all; the actual problem is that I can't convert the given string into the 2dimentional array it wants me to. The problem's running time has to be O(nlogn) which is why I can't use multiple loops for this solution. The input string would be something like:

[[0,2,3],[2,5,3] , [1,2022,5] , [2,5,77]]

And I have to put it into a two dimentional array like so. I saw a few question on stackoverflow like this one, but I can't get the solutions right on Java, that's why I asked this question. So here is what I have done by far (which I'm super ashamed of):

   public static void main(String[] args) {
    
    Scanner scan = new Scanner(System.in);
    
    String inputs = scan.nextLine();
    String[] numbers=new String[100];
    int[][] arr;
    
    numbers=inputs.split("[");
    
    for (String is : numbers) {
        System.out.println(is);
    }
    
    boolean flag=false;
    

    
}

I realised the split function does not work like that.It gives me errors.

Would you please help me convert a given string that has a 2d array like template to an actual 2d array?I'd be very thankful if you'd help.

CodePudding user response:

Try this.

String input = "[[0,2,3],[2,5,3] , [1,2022,5] , [2,5,77]]";

int[][] output = Stream.of(input.replaceAll("\\s", "").split("\\],\\["))
    .map(row -> Stream.of(row.replaceAll("[\\[\\]]", "").split(","))
        .mapToInt(e -> Integer.parseInt(e))
        .toArray())
    .toArray(int[][]::new);

System.out.println(Arrays.deepToString(output));

output:

[[0, 2, 3], [2, 5, 3], [1, 2022, 5], [2, 5, 77]]

CodePudding user response:

Some sort of loops would be needed anyway if array is expected because it would be needed to iterate the input string until a closing bracket ] is detected along with counting the number of numbers in the subarray, and then the numbers should be parsed one by one inside the "subarray" substring.

A solution based on the regular expression and Stream API may look like this:

  • find a match for a subarray
  • parse separate digits in the substring and create a subarray
  • create the resulting 2D array
public static int[][] readArray(String str) {
    Pattern pArr = Pattern.compile("\\[\\s*\\]|\\[\\s*([ -]?\\d )(\\s*,\\s*[ -]?\\d )*\\]");
    Pattern pInt = Pattern.compile("[ -]?\\d ");
    return pArr.matcher(str).results()
        .map(arr -> pInt.matcher(arr.group()).results()
                        .map(MatchResult::group)
                        .mapToInt(Integer::parseInt).toArray()
        )
        .toArray(int[][]::new);
}

Test

System.out.println(Arrays.deepToString(readArray(" [[], [0], [-1,  1], [ 1, 2, 3, -10 ]] ")));
[[], [0], [-1, 1], [1, 2, 3, -10]]

  • Related