#2 Finding a Common Character in Three Strings using Java (Without Using a Method)
Problem Statement:
Given three input strings, our task is to identify a character that is present in all three strings. If such a character exists, we'll return it. If no common character is found, we'll return -1.
Example:
Input:
String 1: "123"
String 2: "345"
String 3: "563"
Recommended by LinkedIn
Output: '3'
public class CommonCharacterFinderWithoutMethod {
public static void main(String[] args) {
String inputStr1 = "123";
String inputStr2 = "345";
String inputStr3 = "563";
boolean commonFound = false;
for (char c : inputStr1.toCharArray()) {
boolean foundInStr2 = false;
boolean foundInStr3 = false;
for (char c2 : inputStr2.toCharArray()) {
if (c == c2) {
foundInStr2 = true;
break;
}
}
for (char c3 : inputStr3.toCharArray()) {
if (c == c3) {
foundInStr3 = true;
break;
}
}
if (foundInStr2 && foundInStr3) {
System.out.println("Common character found: " + c);
commonFound = true;
break;
}
}
if (!commonFound) {
System.out.println("No common character found.");
}
}
}
Explanation:
In this solution, we've opted for a direct approach without utilizing a separate method. The key element is the nested loop structure that allows us to compare characters across the three input strings—inputStr1, inputStr2, and inputStr3. Let's break down the explanation into steps:
By using this direct approach, we demonstrate how to efficiently find a common character among three input strings in Java without the use of a inbuilt method.