Check if the given string is linear or not
Given string str, the task is to check whether the given string is linear or not. If it is linear then print “Yes” else print “No”.
Let the string be “abcdefghij”. It can be broken as:
“a”
“bc”
“def”
“ghij”
if the character a, b, c, and are equal then the given string is linear otherwise not.
Therefore if the string is of the form “xxaxabcxabcdxabcdexab…” then it is called as the linear string.
Examples:
Input: str = “aapaxyayziabcde”
Output: Yes
Explanation:
a
ap
axy
ayzi
abcde
All the broken string have same character as the first character.
Input: str = “bbobfycd”
Output: No
Explanation:
b
bo
bfy
cd
Here b=b=b!=c
Approach: To check if the given string is of the form “xxaxabcxabcdxabcdexab…” then we have to check if characters at index 0, 1, 3, 6, 10, … are equals or not.
If all the characters at the above indexes are equal then the given string is Linear String otherwise it is not.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int is_linear(string s)
{
int tmp = 0;
char first = s[0];
for ( int pos = 0; pos < s.length();
pos += tmp) {
if (s[pos] != first) {
return false ;
}
tmp++;
}
return true ;
}
int main()
{
string str = "aapaxyayziabcde" ;
if (is_linear(str)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
return 0;
}
|
Java
import java.util.*;
class GFG{
static boolean is_linear(String s)
{
int tmp = 0 ;
char first = s.charAt( 0 );
for ( int pos = 0 ; pos < s.length();
pos += tmp)
{
if (s.charAt(pos) != first)
{
return false ;
}
tmp++;
}
return true ;
}
public static void main(String[] args)
{
String str = "aapaxyayziabcde" ;
if (is_linear(str))
{
System.out.println( "Yes" );
}
else
{
System.out.println( "No" );
}
}
}
|
Python3
def is_linear(s):
tmp = 0
first = s[ 0 ]
pos = 0
while pos < len (s):
if (s[pos] ! = first):
return False
tmp + = 1
pos + = tmp
return True
if __name__ = = '__main__' :
str = "aapaxyayziabcde"
if (is_linear( str )):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG{
static bool is_linear(String s)
{
int tmp = 0;
char first = s[0];
for ( int pos = 0; pos < s.Length;
pos += tmp)
{
if (s[pos] != first)
{
return false ;
}
tmp++;
}
return true ;
}
public static void Main(String[] args)
{
String str = "aapaxyayziabcde" ;
if (is_linear(str))
{
Console.Write( "Yes" );
}
else
{
Console.Write( "No" );
}
}
}
|
Javascript
<script>
function is_linear(s)
{
let tmp = 0;
let first = s[0];
for (let pos = 0; pos < s.length;
pos += tmp)
{
if (s[pos] != first)
{
return false ;
}
tmp++;
}
return true ;
}
let str = "aapaxyayziabcde" ;
if (is_linear(str))
{
document.write( "Yes" );
}
else
{
document.write( "No" );
}
</script>
|
Time Complexity: O(log N)
Auxiliary Space: O(1)
Last Updated :
11 May, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...