📜  使用Java的Split函数在矩阵中搜索字符串

📅  最后修改于: 2022-05-13 01:57:24.057000             🧑  作者: Mango

使用Java的Split函数在矩阵中搜索字符串

给定一个字符串str和一个小写英文字母矩阵mat[][] ,任务是找出字符串str是否出现在矩阵中(按行或按列)。

例子:

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

方法:
如果搜索字符串存在于矩阵的任何行中,split函数将产生以下结果:

  1. 如果字符串占据整行,则 split函数将返回一个长度为零的数组。
  2. 如果字符串存在于字符之间,则数组长度将大于 1。
  3. 如果数组长度为 1,则可能存在三种可能的情况 -
    • 字符串出现在前半部分。
    • 字符串出现在下半场。
    • 该字符串不存在于该行中。
  4. 要按列搜索字符串转置矩阵并重复第一步。
  5. 如果找到字符串,则打印Yes否则打印No

下面是上述方法的实现:

// 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");
    }
}
输出:
Yes

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程