leetcode.com/problems/check-if-two-string-arrays-are-equivalent/

 

Check If Two String Arrays are Equivalent - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

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.

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.

java의 new는 cost가 높다.
String 같은 경우 concat을 이용하여 스트링을 붙일 수 있지만 new String()을 하게 된다.
따라서 StringBuilder을 이용하는 것이 메모리와 속도가 절약된다.

class Solution {
	public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
		StringBuilder sb1 = new StringBuilder();
		StringBuilder sb2 = new StringBuilder();

		for (int i = 0; i < word1.length; i++) {
			sb1.append(word1[i]);
		}

		for (int i = 0; i < word2.length; i++) {
			sb2.append(word2[i]);
		}

		String str1 = sb1.toString();
		String str2 = sb2.toString();

		return str1.equals(str2);
	}
}

+ Recent posts