Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
3 views11 pages

Java 1-4

The document outlines four Java programming exercises: reading user details from command line arguments, finding the longest substring without repeating characters, validating parentheses in a string, and generating letter combinations from a phone number. Each exercise includes a code implementation and example outputs. The document serves as a guide for practicing Java programming skills.

Uploaded by

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

Java 1-4

The document outlines four Java programming exercises: reading user details from command line arguments, finding the longest substring without repeating characters, validating parentheses in a string, and generating letter combinations from a phone number. Each exercise includes a code implementation and example outputs. The document serves as a guide for practicing Java programming skills.

Uploaded by

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

Lab programs week-1

1. Write a java program which reads your name and other details
through command line and print them.

public class CommandLineInput


{
public static void main(String[] args)
{
// Check if command line arguments are provided
if (args.length< 4)
{
System.out.println("Please provide your name, age , gender ,
occupation as command line arguments.");
return;
}

// Retrieve details from command line arguments


String name = args[0];
int age = Integer.parseInt(args[1]);
String gender = args[2];
String occupation = args[3];

// Print the details


System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("gender: " + gender);
System.out.println("Occupation: " + occupation);
}
}

// An argument passed when a Java program is run is called a


command line argument.
Output :

>javac CommandLineInput.java

>java CommandLineInputsri25 female Professor

Name: sri
Age: 25
gender: female
Occupation: Professor
2. Write a program to find the longest Substring without
Repeating Characters .

Ex: Input: abcabcbb output:3 string: abc


Input: pwwkew output:3 string: wke
Note: pwke is not a substring , it is a subsequence

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

public class LongestSubstringWithoutRepeatingChars {


public static String longestSubstring(String s) {
if (s == null || s.isEmpty()) {
return "";
}

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


int longestSubstringLength = 0;
int start = 0;
int startIndex = 0;
int endIndex = 0;

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


char ch = s.charAt(i);

if (charPosMap.containsKey(ch)) {
// Update the start index to the next index after the last
occurrence of the repeated character
start = Math.max(start, charPosMap.get(ch) + 1);
}

charPosMap.put(ch, i);

// Calculate the length of the current substring without


repeating characters
int currentLength = i - start + 1;

if (currentLength > longestSubstringLength) {


longestSubstringLength = currentLength;
startIndex = start;
endIndex = i;
}
}

return s.substring(startIndex, endIndex + 1);


}

public static void main(String[] args) {


String input = "abcdabcbbbbb"; // Replace with your string
String longestSubstr = longestSubstring(input);
System.out.println("Longest substring without repeating
characters: " + longestSubstr);
}
}
3. Write a program to find the Valid Parentheses
Given a string containing just the
characters '(', ')', '{', '}', '[' and ']', determine if the input string is
valid. An input string is valid if:

1. Open brackets must be closed by the same type of brackets.


2. Open brackets must be closed in the correct order.

Note that an empty string is also considered valid. Input:( )


Input: ( { ) } Output: Not valid output: valid

importjava.util.Stack;

public class ValidParentheses


{
public static void main(String[] args)
{
System.out.println(isValid("()")); // Output: true
System.out.println(isValid("({)}")); // Output: false
}

public static booleanisValid(String s) {


// Create a stack to store open parentheses
Stack<Character> stack = new Stack<>();

// Iterate through each character in the string


for (char c : s.toCharArray()) {
if (c == '(' || c == '{' || c == '[') {
// If an open parenthesis is encountered, push it onto the
stack
stack.push(c);
} else if (c == ')' && !stack.isEmpty() &&stack.peek() == '(')
{
// If a closing parenthesis is encountered and it matches with
the top of the stack, pop it
stack.pop();
} else if (c == '}' && !stack.isEmpty() &&stack.peek() == '{')
{
// If a closing curly brace is encountered and it matches with
the top of the stack, pop it
stack.pop();
} else if (c == ']' && !stack.isEmpty() &&stack.peek() == '[')
{
// If a closing square bracket is encountered and it matches
with the top of the stack, pop it
stack.pop();
} else {
// If none of the valid cases is met, the parentheses are not
valid
return false;
}
}
// The parentheses are valid if the stack is empty at the end
returnstack.isEmpty();
}
}

Output:

true
false
4. Letter Combinations of a Phone Number
Given a string containing digits from 2-9 inclusive, return all
possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is
given below. Note that 1 does not map to any letters.
Example: Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;

public class LetterCombinations


{
public static void main(String[] args)
{
List<String> result = letterCombinations("23");
System.out.println(result);
}

public static List<String>letterCombinations(String digits)


{
List<String> result = new ArrayList<>();

if (digits == null || digits.length() == 0)


{
return result;
}

// Create a mapping of digits to letters


Map<Character, String>digitToLetters = new HashMap<>();
digitToLetters.put('2', "abc");
digitToLetters.put('3', "def");
digitToLetters.put('4', "ghi");
digitToLetters.put('5', "jkl");
digitToLetters.put('6', "mno");
digitToLetters.put('7', "pqrs");
digitToLetters.put('8', "tuv");
digitToLetters.put('9', "wxyz");

generateCombinations("", digits, 0, digitToLetters, result);

return result;
}

private static void generateCombinations(String current, String digits,


int index,
Map<Character, String>digitToLetters, List<String>
result)
{
// If the current combination has the same length as the input
digits,
//add it to the result
if (index == digits.length())
{
result.add(current);
return;
}

// Get the letters associated with the current digit


char digit = digits.charAt(index);
String letters = digitToLetters.get(digit);

// Recursively generate combinations for the next digit


for (inti = 0; i<letters.length(); i++)
{
generateCombinations(current + letters.charAt(i), digits, index + 1,
digitToLetters, result);
}
}
}
Output:

[ad, ae, af, bd, be, bf, cd, ce, cf]

You might also like