Sitemap
chiang-sh

chiang-sh

LeetCode Notes: String

2 min readDec 30, 2025

--

#242 Valid Anagram

An anagram is a string formed by rearranging the characters of another string. We can use an array to store the frequency of each ASCII character. First, iterate through the first string and increment the count for each character in the array. Then, iterate through the second string and decrement the corresponding counts. Finally, check the array: if all values are 0, the two strings are anagrams.

  • Time Complexity: O(n)
  • Space Complexity: O(1)
class Solution {
public boolean isAnagram(String s, String t) {
int[] alphabets = new int[26];
for (int i = 0; i < s.length(); i++) {
alphabets[s.charAt(i) - 'a']++;
}
for (int i = 0; i < t.length(); i++) {
alphabets[t.charAt(i) - 'a']--;
}
for (int i : alphabets) {
if (i != 0) {
return false;
}
}
return true;
}
}

#125 Valid Palindrome

A palindrome is a string that reads the same forward and backward. This problem requires additional logic because the input string may contain non-alphanumeric characters and mixed casing. We can use two pointers to track the characters. When we met a non-alphanumeric character in the loop, skip it. Once both pointers are pointing to alphanumeric characters, we can compare them (ignoring case).

    Get chiang-sh’s stories in your inbox

    Join Medium for free to get updates from this writer.

  • Time Complexity: O(n)
  • Space Complexity: O(1)
class Solution {
public boolean isPalindrome(String s) {
int left = 0;
int right = s.length() - 1;

while (left < right) {
if (!Character.isLetterOrDigit(s.charAt(left))) {
left++;
continue;
}
if (!Character.isLetterOrDigit(s.charAt(right))) {
right--;
continue;
}
if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
return false;
}
left++;
right--;
}
return true;
}
}

#3 Longest Substring Without Repeating Characters

We can use an array to record the last seen index of each character, and a pointer to track the start index of the substring. During the iteration, if a character has appeared before and its recorded index is greater than or equal to the start index, it means that the current substring contains a duplicate. In this case, we update the start index. We then calculate the current substring length and compare it to the current maximum length found so far, and update it if needed.

  • Time Complexity: O(n)
  • Space Complexity: O(1)
class Solution {
public int lengthOfLongestSubstring(String s) {
int[] array = new int[128];
Arrays.fill(array, -1);
int maxLen = 0;
int start = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
start = array[c] + 1 > start ? array[c] + 1 : start;
if (i - start + 1 > maxLen) {
maxLen = i - start + 1;
}
array[c] = i;
}
return maxLen;
}
}

--

--