Given two strings, determine if they share a common substring. A substring may be as small as one character.
Example:
Input: s1="hello", s2="world"
Output: YES
Approach
Java
import java.util.HashSet;public class TwoStrings {public static void main(String[] args) {String s1 = "hi";String s2 = "world";String result = twoStrings(s1, s2);System.out.println(result);}public static String twoStrings(String s1, String s2) {HashSet<Character> set = new HashSet<Character>();for (int i = 0; i < s1.length(); i++) {set.add(s1.charAt(i));}for (int i = 0; i < s2.length(); i++) {if (set.contains(s2.charAt(i))) {return "YES";}}return "NO";}}
C++
#include <bits/stdc++.h>using namespace std;string twoStrings(string s1, string s2){int f1[26] = {0}, f2[26] = {0};for (int i = 0; i < s1.size(); i++){f1[s1[i] - 'a']++;}for (int i = 0; i < s2.size(); i++){f2[s2[i] - 'a']++;}for (int i = 0; i < 26; i++){if (f1[i] > 0 && f2[i] > 0){return "YES";}}return "NO";}int main(){string s1 = "hello";string s2 = "world";string result = twoStrings(s1, s2);cout << result << "\n";return 0;}
No comments:
Post a Comment