leetcode.com/problems/check-if-two-string-arrays-are-equivalent/
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);
}
}
'개발자 > algorithm' 카테고리의 다른 글
LeetCode, Merge Two Binary Trees (Java) (0) | 2021.01.03 |
---|---|
LeetCode, Custom Sort String (Java) (0) | 2020.12.30 |
LeetCode, Minimum Number of Steps to Make Two Strings Anagram (Java) (0) | 2020.12.29 |
LeetCode, Goal Parser Interpretation (Java) (0) | 2020.12.29 |
LeetCode, Remove Duplicates from Sorted Array (Java) (0) | 2020.12.22 |