0% found this document useful (0 votes)
6 views

LeetCodeSolutions

The document contains five coding problems with their respective solutions in Java. The problems include finding the longest palindromic substring, decoding a string, grouping anagrams, finding the minimum window substring, and converting a string to a zigzag pattern. Each problem is accompanied by example inputs and outputs, as well as constraints on the input values.

Uploaded by

lokesh31052k3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

LeetCodeSolutions

The document contains five coding problems with their respective solutions in Java. The problems include finding the longest palindromic substring, decoding a string, grouping anagrams, finding the minimum window substring, and converting a string to a zigzag pattern. Each problem is accompanied by example inputs and outputs, as well as constraints on the input values.

Uploaded by

lokesh31052k3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 6

1.

Longest Palindromic Substring


💡 Problem:
Given a string s, return the longest palindromic substring in s.
🔹 Example:
Input: s = "babad"
Output: "bab"
Explanation: "aba" is also a valid answer.
🔹 Constraints:
• 1 <= s.length <= 1000
• s consists only of lowercase English letters.

package com.htc.leetcodesolutions.main;

public class LongestPalindromicSubstring {

public static void main(String[] args) {

String input = "babad";


System.out.println("Longest Palindromic Substring: " +
findLongestPalindromeSubstring(input));
}

public static String findLongestPalindromeSubstring(String input) {

if (input.length() > 1) {

int start = 0;
int end = 0;

for (int i = 0; i < input.length(); i++) {

int evenLengthPalindrome = findLengthOfPalindrome(input, i,


i);
int oddLengthPalindrome = findLengthOfPalindrome(input, i,
i + 1);
int length = Math.max(evenLengthPalindrome,
oddLengthPalindrome);

if (length > end - start) {

start = i - (length - 1) / 2;
end = i + length / 2;
}
}
return input.substring(start, end + 1);
} else {
return "Input String should contains minimum 2 characters";
}
}

public static int findLengthOfPalindrome(String input, int left, int right) {

while (left >= 0 && right < input.length() && input.charAt(left) ==


input.charAt(right)) {
left--;
right++;
}
return right - left - 1;
}

===================================================================================
====

2. Decode String
💡 Problem:
Given an encoded string, return its decoded form.
The encoding rule is: k[encoded_string], where encoded_string inside the brackets
is repeated k times.
You may assume that the input string is always valid.
🔹 Example:
Input: s = "3[a]2[bc]"
Output: "aaabcbc"
🔹 Constraints:
• 1 <= s.length <= 30
• s contains only digits, square brackets, and lowercase English letters.

package com.htc.leetcodesolutions.main;

import java.util.Stack;

public class StringDecode {

public static void main(String[] args) {


String input = "3[a2[c]]";
System.out.println(stringDecode(input));
}

public static String stringDecode(String input) {

Stack<Integer> numberStack = new Stack<>();


Stack<StringBuilder> stringStack = new Stack<>();
StringBuilder stringBuilder = new StringBuilder();
int num = 0;

for (char ch : input.toCharArray()) {


if (Character.isDigit(ch)) {
num = num * 10 + (ch - '0');
} else if (ch == '[') {
numberStack.push(num);
num = 0;
stringStack.push(stringBuilder);
stringBuilder = new StringBuilder();
} else if (ch == ']') {
int k = numberStack.pop();
StringBuilder temp = stringBuilder;
stringBuilder = stringStack.pop();

while (k-- > 0) {


stringBuilder.append(temp);
}
} else {
stringBuilder.append(ch);
}
}

return stringBuilder.toString();
}
}
===================================================================================
======

3. Group Anagrams
💡 Problem:
Given an array of strings strs, group anagrams together.
An anagram is a word or phrase formed by rearranging the letters of a different
word.
🔹 Example:
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
🔹 Constraints:
• 1 <= strs.length <= 10^4
• strs[i] consists of lowercase English letters.

package com.htc.leetcodesolutions.main;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GroupAnagrams {

public static void main(String[] args) {

String[] wordsArray = { "eat", "tea", "tan", "ate", "nat", "bat" };


System.out.println(groupAnagrams(wordsArray));
}

public static List<List<String>> groupAnagrams(String[] wordsArray){

Map<String, List<String>> anagramMap = new HashMap<>();

for(String word : wordsArray) {


char[] characters = word.toCharArray();
Arrays.sort(characters);
String sortedWord = new String(characters );

anagramMap.putIfAbsent(sortedWord, new ArrayList<>());


anagramMap.get(sortedWord).add(word);

}
return new ArrayList<>(anagramMap.values());
}

===================================================================================
============
4. Minimum Window Substring
💡 Problem:
Given two strings s and t, return the minimum window substring of s that contains
all characters of t.
If there is no such substring, return "" (empty string).
🔹 Example:
Input: s = "ADOBECODEBANC", t = "ABC"
Output: "BANC"
🔹 Constraints:
• 1 <= s.length, t.length <= 10^5
• s and t consist of uppercase and lowercase English letters.

package com.htc.leetcodesolutions.main;

import java.util.HashMap;
import java.util.Map;

public class MinWindowSubstring {


public static void main(String[] args) {
String s = "ADOBECODEBANC";
String t = "ABC";

System.out.println(minWindow(s, t));
}

public static String minWindow(String s, String t) {


if (s.length() < t.length())
return "";

Map<Character, Integer> tMap = new HashMap<>();


for (char c : t.toCharArray()) {
tMap.put(c, tMap.getOrDefault(c, 0) + 1);
}

int left = 0, right = 0, minLen = Integer.MAX_VALUE;


int start = 0;
int required = tMap.size();
int formed = 0;
Map<Character, Integer> windowMap = new HashMap<>();

while (right < s.length()) {


char c = s.charAt(right);
windowMap.put(c, windowMap.getOrDefault(c, 0) + 1);

if (tMap.containsKey(c) && windowMap.get(c).intValue() ==


tMap.get(c).intValue()) {
formed++;
}

while (formed == required) {


if (right - left + 1 < minLen) {
minLen = right - left + 1;
start = left;
}

char leftChar = s.charAt(left);


windowMap.put(leftChar, windowMap.get(leftChar) - 1);
if (tMap.containsKey(leftChar) && windowMap.get(leftChar) <
tMap.get(leftChar)) {
formed--;
}

left++;
}

right++;
}

return minLen == Integer.MAX_VALUE ? "" : s.substring(start, start +


minLen);
}
}

=========================================================

5. Zigzag Conversion
💡 Problem:
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of
rows.
You need to return the converted string when read row-wise.
🔹 Example:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Explanation:
P A H N
A P L S I I G
Y I R
🔹 Constraints:
• 1 <= s.length <= 1000
• 1 <= numRows <= 1000

package com.htc.leetcodesolutions.main;

public class ZigzagConversion {


public static void main(String[] args) {
String s = "PAYPALISHIRING";
int numRows = 3;
System.out.println(convert(s, numRows));
}

public static String convert(String s, int numRows) {


if (numRows == 1 || s.length() <= numRows) {
return s;
}

StringBuilder[] rows = new StringBuilder[numRows];


for (int i = 0; i < numRows; i++) {
rows[i] = new StringBuilder();
}

int index = 0;
boolean down = true;
for (char c : s.toCharArray()) {
rows[index].append(c);

if (index == 0) {
down = true;
} else if (index == numRows - 1) {
down = false;
}

index += down ? 1 : -1;


}

StringBuilder result = new StringBuilder();


for (StringBuilder row : rows) {
result.append(row);
}

return result.toString();
}
}

You might also like