chandanbaranwal
BAN USERpublic class CompressString
{
public static void main(String[] args)
{
System.out.println("[CompressString] in main()");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string:");
try {
String str= br.readLine();
StringBuffer strBuff=new StringBuffer();
strBuff.append(str.charAt(0));
int len=str.length();
for(int i=1;i<len;)
{
char ch=str.charAt(i);
char chBuff=strBuff.charAt(strBuff.length()-1);
if(ch==chBuff)
{
int num=1;
strBuff.append(num);
while(ch==chBuff )
{
num++;
strBuff.deleteCharAt(strBuff.length()-1);
strBuff.append(num);
i++;
if(i<len)
ch=str.charAt(i);
else
break;
}
}
else
{
strBuff.append(ch);
i++;
}
}
System.out.println("Output String : "+strBuff);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
With better time complexity than previous:
public class FirstNonRepeatingChar
{
public static void main(String[] args)
{
System.out.println("[FirstNonRepeatingChar] in main()");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string:");
try {
String str= br.readLine();
Map<Character,Integer> map = new HashMap();
for( int i=0;i<str.length();i++ )
{
Character ch =str.charAt(i);
if(map.get(ch)==null)
map.put(ch, 1);
else
map.put(ch, map.get(ch)+1);
}
int i=0;
for( ;i<str.length();i++ )
{
Character ch =str.charAt(i);
if(map.get(ch)==1)
{
System.out.println("First Non-repeated character is: "+ch);
break;
}
}
if(i==str.length())
{
System.out.println("No Non-repeated character ");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I am assuming that we want to show the first char comin in input string that is not going to be repeated:
public class FirstNonRepeatingChar
{
public static void main(String[] args)
{
System.out.println("[FirstNonRepeatingChar] in main()");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the string:");
try {
String str= br.readLine();
int i=0;
for( ;i<str.length()-1;i++ )
{
Character ch =str.charAt(i);
if(!(str.substring(i+1).contains(ch.toString()) || str.substring(0,i).contains(ch.toString()) ))
{
System.out.println("First Non-repeated character is: "+ch);
break;
}
}
if(i==str.length()-1)
{
System.out.println("No Non-repeated character ");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
its a permutation combination problem.....
- chandanbaranwal May 04, 2012with m-rows and n-columns.....the total number of steps to reach end point from start point is ((m-1)+(n-1)).......now the numbers of ways is actually the number of arrangements for this number of steps.....which is
!(m+n-2)/((!(m-1))*(!(n-1)))