Contents

Substring 2 (with.Java)

   Dec 1, 2023     1 min read

This is a recap of the “Substring 2” problem.

We’re going to learn about it by solving coding test problems, reflecting on the problems we solved, and exploring other ways to solve them.

Let’s start with the problem.

Problem

A string A is said to be a substring of B if it is contained within another string B.

For example, the string “abc” is a substring of the string “aabcc”.

Given strings str1 and str2, complete the solution function so that it returns 1 if str1 is a substring of str2 and 0 if it is not.

Example input and output

str1str2result
“abc”“aabcc”1
“tbt”“tbbttb”0

My solution to the ### problem

class Solution {
    public int solution(String str1, String str2) {
        int answer;
        answer = str2.contains(str1) ? 1 : 0 ;
        return answer;
    }
}

Solution

int answer;: Declare an integer variable answer to store the result.

answer = str2.contains(str1) ? 1 : 0;: str2.contains(str1) determines whether str1 is contained in str2.

If it does, assign 1 to answer; if it doesn’t, assign 0 to answer.

return answer;: Returns an answer value representing the result of the judgment.