-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnagram.java
More file actions
104 lines (101 loc) · 3.08 KB
/
Anagram.java
File metadata and controls
104 lines (101 loc) · 3.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Program: Check if a Sentence is an Anagram and Find Longest & Shortest Words
// Topic: String Handling
// Description: Accepts a sentence as input, identifies the longest and shortest words,
// and checks if the sentence contains all letters of the English alphabet (an anagram/pangram check).
// Demonstrates string traversal, character comparison, and use of HashSet for unique character validation.
package stringhandling;
import java.util.*;
/**
*
* @author Samim
*/
public class Anagram {
String l="";
String StringStructure(String s){
for(int i=0;i<s.length();i++){
for(int j=i+1;j<s.length();j++){
if(s.charAt(i)!=' '){
if(s.charAt(i)==s.charAt(j)){
s=s.substring(0,j)+s.substring(j+1);
}
}
}
}
return s;
}
boolean isAnagram(String s){
int counter=0;
for(char i='a';i<='z';i++){
for(int j=0;j<s.length();j++){
if(s.charAt(j)!=' '){
if(s.charAt(j)==i){
//System.out.println(s.charAt(j)+" : "+(i));
counter++;
}
}
}
}
return counter==26;
}
void longest(String s){
String w="";
for(int i=0;i<s.length();i++){
if(s.charAt(i)!=' '){
w+=s.charAt(i);
}
else{
if(l.length()<w.length()){
l=w;
}
w="";
}
}
System.out.println("Longest Word :"+l);
}
void shortest(String s){
String sh=l;
String w="";
for(int i=0;i<s.length();i++){
if(s.charAt(i)!=' '){
w+=s.charAt(i);
}
else{
if(sh.length()>w.length()){
sh=w;
}
w="";
}
}
System.out.println("Shortest WOrd :"+sh);
}
boolean anagramTest(String s){
Set<Character> t=new HashSet();
for(int i=0;i<s.length();i++){
if(s.charAt(i)!=' ')
t.add(s.charAt(i));
}
return t.size()==26;
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String s,stest;
System.out.println("Enter The Sentence :");
s=sc.nextLine();
Anagram obj=new Anagram();
obj.longest(s);
obj.shortest(s);
stest=obj.StringStructure(s);
if(obj.isAnagram(stest)==true){
System.out.println("Sentence is anagram !");
}
else{
System.out.println("Sentence is not anagram !");
}
if(obj.anagramTest(s)==true){
System.out.println("Sentence is anagram !");
}
else{
System.out.println("Sentence is not anagram !");
}
}
}