原文:

给定一个字符序列,在一行中打印连续的字符序列,否则 在新的一行中打印。

示例:

input  : abcxyzaccd
output : abc
         xyz
         a
         c
         cd
input : abczyxaccd
output: abc
        zyx
        a
        c
        cd

想法是从左到右遍历字符串。对于每个遍历的字符,如果它与前一个字符连续,则打印一行,否则打印一个新的行字符。

c

// c   program to print consecutive characters
// together in a line.
#include 
using namespace std;
void print(string str)
{
    cout << str[0];
    for (int i=1; str[i]!='\0'; i  )
    {
        if ((str[i] == str[i-1] 1) ||
            (str[i] == str[i-1]-1))
            cout << str[i];
        else
            cout << "\n" << str[i];;
    }
}
// driver code
int main()
{
    string str = "abcxyzaccd";
    print(str);
    return 0;
}

java 语言(一种计算机语言,尤用于创建网站)

// java program to print consecutive characters
// together in a line.
class gfg {
    static void print(string str1) {
        char str[] = str1.tochararray();
        system.out.print(str[0]);
        for (int i = 1; i < str.length; i  ) {
            if ((str[i] == str[i - 1]   1)
                    || (str[i] == str[i - 1] - 1)) {
                system.out.print(str[i]);
            } else {
                system.out.print("\n"   str[i]);
            }
        }
    }
// driver code
    public static void main(string[] args) {
        string str = "abcxyzaccd";
        print(str);
    }
}
// this code is contributed by 29ajaykumar

python 3

# python3 program to print consecutive characters
# together in a line.
def _print(string):
    print(string[0], end = "")
    for i in range(1, len(string)):
        if (ord(string[i]) == ord(string[i - 1])   1 or
            ord(string[i]) == ord(string[i - 1]) - 1):
            print(string[i], end = "")
        else:
            print()
            print(string[i], end = "")
# driver code
if __name__ == "__main__":
    string = "abcxyzaccd"
    _print(string)
# this code is contributed by
# sanjeev2552

c

// c# program to print consecutive characters
// together in a line.
using system;
class gfg
{
    static void print(string str1)
    {
        char []str = str1.tochararray();
        console.write(str[0]);
        for (int i = 1; i < str.length; i  )
        {
            if ((str[i] == str[i - 1]   1)
                    || (str[i] == str[i - 1] - 1))
            {
                console.write(str[i]);
            }
            else
            {
                console.write("\n"   str[i]);
            }
        }
    }
    // driver code
    public static void main()
    {
        string str = "abcxyzaccd";
        print(str);
    }
}
// this code is contributed by princiraj1992

java 描述语言


输出:

abc
xyz
a
c
cd

时间复杂度: o(n)

本文由拉克什·库马尔供稿。如果你喜欢 geeksforgeeks 并想投稿,你也可以使用写一篇文章或者把你的文章邮寄到 review-team@geeksforgeeks.org。看到你的文章出现在极客博客pg电子试玩链接主页上,帮助其他极客。 如果你发现任何不正确的地方,或者你想分享更多关于上面讨论的话题的信息,请写评论。