A string is considered to be a composite of several maximal segments of identical characters. For example, "aaabbaaac" is a composite of the segments: "aaa", "bb", "aaa" and "c". Given a string, return the average length of all the segments which form that string.
Definition
Class:
StringSegment
Method:
average
Parameters:
String
Returns:
double
Method signature:
double average(String s)
(be sure your method is public)
Notes
-
A return value with either an absolute or relative error of less than 1.0E-9 is considered correct.
Constraints
-
s will contain between 1 and 50 characters, inclusive.
-
s will contain only lowercase letters ('a'-'z').
Examples
0)
"aaabbaaac"
Returns: 2.25
Average length of all the segments = ( 3 + 2 + 3 + 1 ) / 4 = 2.25
1)
"aabbccdd"
Returns: 2.0
2)
"abba"
Returns: 1.3333333333333333
package Test01;
public class Test01 {
public static void main(String args[])
{
String a ="aaaaaa";
System.out.println("res"+average(a));
}
public static double average(String s)
{
//int b =0;
double count=1;
for (int i=1;i<s.length();i++)
{
if (s.charAt(i-1)!=s.charAt(i))
{
count++;
}
//b++;
}
int sum = s.length();
double res = sum/count;
System.out.println("sum"+sum);
System.out.println("count"+count);
System.out.println("res"+res);
return res;
}
}