In this post, we will solve Two Strings HackerRank Solution. This problem (Two Strings) is a part of HackerRank Problem Solving series.
Solution – Two Strings – HackerRank Solution
C++
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; bool check(const string& _a, const string& _b) { // O(n*m) lol no thanks // more like O(n+m+52) bool arr[52] = {false}; for(auto& a : _a) arr[a - 'a'] = true; for(auto& b : _b) arr[b - 'a' + 26] = true; for(int i = 0; i < 26; i++) if (arr[i] && arr[i+26]) return true; return false; } int main() { int t; cin >> t; string a, b; while (t-- > 0) { cin >> a >> b; cout << (check(a,b) ? "YES" : "NO") << endl; } return 0; }
Python
cases = int(input()) offset = ord('a') for caseNo in range(cases): a = input() b = input() sa = [False] * 26 sb = [False] * 26 for char in a: sa[ord(char) - offset] = True for char in b: sb[ord(char) - offset] = True for i in range(26): if sa[i] and sb[i]: print("YES") break else: print("NO")
Java
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { static String twoStrings(String s1, String s2){ int[] cache = new int[256]; for (int i = 0; i < s1.length(); i++) { cache[(int)s1.charAt(i)]++; } for (int i = 0; i < s2.length(); i++) { if (cache[(int)s2.charAt(i)] != 0) { return "YES"; } } return "NO"; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int q = in.nextInt(); for(int a0 = 0; a0 < q; a0++){ String s1 = in.next(); String s2 = in.next(); String result = twoStrings(s1, s2); System.out.println(result); } } }
Note: This problem (Two Strings) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.