Contents

Find the desired string (with.Java)

   Oct 10, 2023     1 min read

In this article, we learned about finding a string.

We’ll do this by solving a coding test problem, doing a retrospective on the problem we solved, and learning about other ways to solve it.

Let’s start with the problem.

Problem

You are given two alphabetical strings, myString and pat.

Complete a solution function that returns 1 if pat exists in any consecutive substring of myString, and 0 otherwise.

Note that we do not distinguish between upper and lower case letters of the alphabet.

Example input and output
myStringpatreturn
“AbCdEfG”“aBc”1
“aaAA”“aaaaa”0

My solution to the problem

class Solution {
    public int solution(String myString, String pat) {
        int answer = 0;
        String lowerStr = myString.toLowerCase();
        String lowerPat = pat.toLowerCase();
        if(lowerStr.contains(lowerPat)){
            answer = 1;
        }
        } return answer;
    }
}
Solution description

int answer = 0;: Initialize the variable answer to store the result. The initial value is 0.

String lowerStr = myString.toLowerCase();: Convert the input string myString to lowercase and store it in lowerStr. The reason for doing this is to make judgments case insensitive.

String lowerPat = pat.toLowerCase();: Convert the input string pat to lowercase as well and store it in lowerPat.

if(lowerStr.contains(lowerPat)) : If the string lowerStr contains the string lowerPat:

Set answer to 1.

return answer;: Returns answer representing the result.

If lowerStr contains lowerPat, return 1; otherwise, return 0.