The problem statement is copy pasted from leetcode as it is:
Given two string arrays word1
and word2
, return true
if the two arrays represent the same string, and false
otherwise.
A string is represented by an array if the array elements concatenated in order forms the string.
Example 1:
Input: word1 = ["ab", "c"], word2 = ["a", "bc"] Output: true Explanation: word1 represents string "ab" + "c" -> "abc" word2 represents string "a" + "bc" -> "abc" The strings are the same, so return true.
Example 2:
Input: word1 = ["a", "cb"], word2 = ["ab", "c"] Output: false
Example 3:
Input: word1 = ["abc", "d", "defg"], word2 = ["abcddefg"] Output: true
Constraints:
1 <= word1.length, word2.length <= 103
1 <= word1[i].length, word2[i].length <= 103
1 <= sum(word1[i].length), sum(word2[i].length) <= 103
word1[i]
andword2[i]
consist of lowercase letters.
My Solution:
package madwani.sushil.leetcode.Jan_8_15_2021;
public class CheckIfTwoStringArraysAreEquivalent {
public static void main(String[] args) {
String[] word1 = new String[] {};
String[] word2 = new String[] {};
System.out.println(arrayStringsAreEqual(word1, word2));
}
public static boolean arrayStringsAreEqual(String[] word1, String[] word2) {
StringBuilder string1 = new StringBuilder();
StringBuilder string2 = new StringBuilder();
int i = 0, j =0;
while (i < word1.length || j < word2.length) {
if (i < word1.length) {
string1.append(word1[i++]);
}
if (j < word2.length) {
string2.append(word2[j++]);
}
}
return string1.toString().equals(string2.toString()) ;
}
}
// time complexity : O(N)
// space complexity: O(1)
public static boolean arrayStringsAreEqual1(String[] word1, String[] word2) {
int k=0, m=0;
for (int i=0, j=0; i< word1.length && j < word2.length;) {
while (k< word1[i].length() && m < word2[j].length()) {
if (word1[i].charAt(k) != word2[j].charAt(m)) {
return false;
}
k++; m++;
}
if ( k == word1[i].length()) {
k = 0; i++;
}
if ( m == word2[j].length()) {
m = 0; j++;
}
}
if ( k !=0 || m !=0) {
return false;
}
return true;
}
No comments:
Post a Comment