Open In App

Search a string in Matrix Using Split function in Java

Last Updated : 18 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string str and a matrix mat[][] of lowercase English alphabets, the task is to find whether the string str appears in the matrix (either row-wise or column-wise). 

Examples:

Input: str = "GFG"
mat[][] = {{'G', 'E', 'E', 'K', 'S'},
{'F', 'O', 'R', 'A', 'N'},
{'G', 'E', 'E', 'K', 'S'}}
Output: Yes
GFG is present in the first column.

Input: str = "SSS"
mat[][] = {{'G', 'E', 'E', 'K', 'S'},
{'F', 'O', 'R', 'A', 'N'},
{'G', 'E', 'E', 'K', 'S'}}
Output: No

Approach 1:

If the search string is present in any row of the matrix the following results will be produced by the split function:

  1. If the string occupies the whole row then the split function will return an array of length zero.
  2. If the string is present in between characters then the array length will be greater than one.
  3. If the array length is one then three possible cases can be there-
    • The string occurs in first half.
    • The string occurs in second half.
    • The string is not present in that row.
  4. To search the string column wise transpose the matrix and repeat step one.
  5. Print Yes if the string is found else print No.

Below is the implementation of the above approach: 

Java
// Java program to search a string in
// the matrix using split function
import java.util.*;
public class GFG {

    // Function to check the occurrence of string in the matrix
    public static int check(String[] matrix, String string)
    {
        // Looping the contents in the matrix
        for (String input : matrix) {

            // using split operator
            String[] value = input.split(string);

            if (value.length >= 2 || value.length == 0) {
                return 1;
            }
            else if (value.length == 1
                    && input.length() != value[0].length()) {
                return 1;
            }
        }
        return 0;
    }

    // Function to transpose the given matrix
    public static String[] vertical(String[] matrix)
    {
        String[] vertical_value = new String[(matrix[0].length())];
        for (int i = 0; i < matrix[0].length(); i++) {
            String temp = "";
            for (int j = 0; j < matrix.length; j++)
                temp += matrix[j].charAt(i);
            vertical_value[i] = temp;
        }

        // returning the transposed matrix
        return vertical_value;
    }

    // Driver code
    public static void main(String[] args)
    {

        // Input matrix of characters
        String[] matrix = { "GEEKS", "FORAN", "GEEKS" };

        // element to be searched
        String search = "GFG";

        // Transpose of the matrix
        String[] verticalMatrix = vertical(matrix);

        // Searching process
        int horizontal_search = check(matrix, search);
        int vertical_search = check(verticalMatrix, search);

        // If found
        if (horizontal_search == 1 || vertical_search == 1)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
Python3
def check(matrix, string):
    # Looping the contents in the matrix
    for input_str in matrix:
        # using split operator
        value = input_str.split(string)

        if len(value) >= 2 or len(value) == 0:
            return 1
        elif len(value) == 1 and len(input_str) != len(value[0]):
            return 1
    return 0

def vertical(matrix):
    vertical_value = ['' for _ in range(len(matrix[0]))]
    for i in range(len(matrix[0])):
        temp = ""
        for j in range(len(matrix)):
            temp += matrix[j][i]
        vertical_value[i] = temp
    return vertical_value

# Input matrix of characters
matrix = ["GEEKS", "FORAN", "GEEKS"]

# element to be searched
search = "GFG"

# Transpose of the matrix
vertical_matrix = vertical(matrix)

# Searching process
horizontal_search = check(matrix, search)
vertical_search = check(vertical_matrix, search)

# If found
if horizontal_search == 1 or vertical_search == 1:
    print("Yes")
else:
    print("No")

Output
Yes

Approach 2:

  1. To check if the given string is present in the matrix, we first perform a horizontal search and then a vertical search.
  2. For horizontal search, we split each row of the matrix using the given string as delimiter. If the resulting array length is greater than or equal to 2 or if it’s empty, we conclude that the string is present horizontally.
  3. Similarly, for vertical search, we transpose the matrix and repeat the horizontal search.


Java
import java.util.*;

public class GFG {

    // Function to search for a string in the matrix
    public static String searchStringInMatrix(String[] matrix, String searchString) {
        // Check horizontally
        int horizontalSearch = check(matrix, searchString);

        // Transpose the matrix for vertical search
        String[] verticalMatrix = vertical(matrix);

        // Check vertically
        int verticalSearch = check(verticalMatrix, searchString);

        // If found in either direction, return "Yes"
        if (horizontalSearch == 1 || verticalSearch == 1)
            return "Yes";
        else
            return "No";
    }

    // Function to check for string occurrence in matrix
    public static int check(String[] matrix, String searchString) {
        for (String row : matrix) {
            String[] substrings = row.split(searchString);

            if (substrings.length >= 2 || substrings.length == 0) {
                return 1;
            } else if (substrings.length == 1 && row.length() != substrings[0].length()) {
                return 1;
            }
        }
        return 0;
    }

    // Function to transpose the matrix
    public static String[] vertical(String[] matrix) {
        String[] verticalMatrix = new String[matrix[0].length()];
        for (int i = 0; i < matrix[0].length(); i++) {
            StringBuilder column = new StringBuilder();
            for (String row : matrix) {
                column.append(row.charAt(i));
            }
            verticalMatrix[i] = column.toString();
        }
        return verticalMatrix;
    }

    // Driver code 
    public static void main(String[] args) {

        // Input matrix of characters 
        String[] matrix = { "GEEKS", "FORAN", "GEEKS" };

        // String to search 
        String searchString = "GFG";

        // Search for the string in the matrix 
        String result = searchStringInMatrix(matrix, searchString);

        // Print the result 
        System.out.println("Output: " + result);
    }
}
// Nikunj Sonigara

Output
Output: Yes


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads